问题
I use mysql.connector
to fetch rows in a python script but when I update a table the I don't see the changes.
My code is:
import mysql.connector
database = mysql.connector.connect(host='localhost', user='root', passwd='password', database='my_db')
cursor = database.cursor()
cursor.execute('SELECT * FROM my_table')
print(cursor.fetchall())
cursor.execute('SELECT * FROM my_table')
print(cursor.fetchall())
In first time it reads the correct values but at the second time it reads the same values as in the first time even though I have updated my_table mysql.connector does not see any changes.
Do anyone have any ideas on how to solve this problem? Thanks!
回答1:
When use performs DML
like update
, delete, etc You have to commit cursor after performing the operation otherwise your operation not save. There are use case of commit cursor some time
- due to the electricity issue
- atomicity transaction will rollback or commit latter
like
import mysql.connector
database = mysql.connector.connect(host='localhost', user='root', passwd='password', database='my_db')
cursor = database.cursor()
try:
cursor.execute("update Employee set name = 'alex' where id = 110")
cursor.commit()
except:
cursor.rollback()
cursor.close()
commit if the update will succeed otherwise rollback if got any error at the database level
or you can pass autocommit=True
when you connect with database it will work too it's global configuration it will commit of some interval of time
like
database = mysql.connector.connect(host='localhost', user='root', passwd='password', database='my_db', autocommit=True)
cursor = database.cursor()
来源:https://stackoverflow.com/questions/65882125/python-module-mysql-connector-does-not-see-new-changes