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.
The above is the detailed content of Why Aren't My Python MySQL Database Updates Reflecting?. For more information, please follow other related articles on the PHP Chinese website!