"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 Aren't My Python MySQL Database Updates Reflecting?

Why Aren't My Python MySQL Database Updates Reflecting?

Published on 2025-01-21
Browse:130

Why Aren't My Python MySQL Database Updates Reflecting?

Issue: Automatic Database Updates Not Occurring with MySQL and Python

When attempting to update a row in a MySQL database via Python code, the database does not automatically reflect the changes. Upon querying the database directly, it is evident that the update has not occurred.

Possible Solution

The issue may stem from not committing the transaction properly. MySQLdb disables autocommit by default. Adding conn.commit() before closing the connection would ensure that the changes are permanently stored in the database.

Modified Code

import MySQLdb

conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname")
cursor=conn.cursor()

cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100")
conn.commit()  # Commit the changes to the database
cursor.execute("SELECT Co_num FROM compinfo WHERE ID=100")
results = cursor.fetchall()

for row in results:
    print row[0]

print "Number of rows updated: %d" % cursor.rowcount

cursor.close()
conn.close()

By committing the transaction before closing the connection, the code should successfully update the database and reflect the changes upon querying directly.

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