"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Are My MySQL Queries from Python Returning Inconsistent Results?

Why Are My MySQL Queries from Python Returning Inconsistent Results?

Published on 2024-11-24
Browse:115

Why Are My MySQL Queries from Python Returning Inconsistent Results?

MySQL Queries from Python Yielding Inconsistencies

Your query is likely not retrieving the most up-to-date data because you're not committing changes to the database. By default, MySQL sets the isolation level to "REPEATABLE READ," which means subsequent queries within the same transaction view the initial snapshot of data rather than any changes made during the transaction.

To ensure that your data is up-to-date, you need to commit the connection after each query. This completes the current transaction and prepares the next transaction to fetch the most recent changes from the database.

Here's an updated version of your code with the necessary commit:

# Main loop
while True:

    # SQL query
    sql = "SELECT * FROM table"

    # Read the database, store as a dictionary
    mycursor = mydb.cursor(dictionary=True)
    mycursor.execute(sql)

    # Store data in rows
    myresult = mycursor.fetchall()

    # Transfer data into list
    for row in myresult:
        myList[int(row["rowID"])] = (row["a"], row["b"], row["c"])

        print(myList[int(row["rowID"])])

    # Commit changes!
    mydb.commit()
    print("---")
    sleep(0.1)

With this modification, your code will now retrieve the latest data from the database during each query loop.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3