Home > Database > Mysql Tutorial > Why Aren't My Python MySQL Database Updates Reflecting?

Why Aren't My Python MySQL Database Updates Reflecting?

Barbara Streisand
Release: 2024-12-04 15:25:15
Original
649 people have browsed it

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template