2

I want to make a python script that consistently checks the Mysql database. The problem that is arising is that the first time checks that there is no data it consistently says there is no data in the database even after I add the data in the database.

But if the data is already there in the database I immediately fetch it and continues.

What can I do such that my python script consistently checks the database and if it finds the data it stops checking the database and continue's

I have tried running it when there is no data in the database and then added data to the database

import mysql.connector



mydb = mysql.connector.connect(
          host='localhost',
          user='root',
          passwd='',
          database='local_data'
        )

mycursor = mydb.cursor()

node_id = 123
node_id = str(node_id)

print('getting code...')

a = 0
while True:
    try:
        time.sleep(1)
        a=a+1
        print(a)
        sql = "SELECT code_name FROM node_code where node_id = '"+node_id +"'"    
        mycursor.execute(sql)
        myresult = mycursor.fetchone()
        for x in myresult:
            filename=x
        print(filename)
        break

    except Exception as error:
        print("Nothing in database\n")
        print(error)

I am expecting an output where it keeps checking the database until it finds the data after which it continues

I am getting these results. By the time the second loop ran the data was inserted in the database

getting code...
1
Nothing in database

'NoneType' object is not iterable
2
Nothing in database

'NoneType' object is not iterable
3
Nothing in database

If the data is already in the database before I run the script I get this

getting code...
1
server.py
2
  • try mycursor.commit() at the end of the while loop Commented May 8, 2019 at 12:05
  • this tell me why... supporting other people say do conn.commit() stackoverflow.com/questions/21974169/… Commented May 8, 2019 at 12:07

1 Answer 1

0

This is because the transaction has not ended unless you do a commit to end that transaction. Try committing that transaction by doing mycursor.commit() at the end of loop

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.