Python Module Mysql-connector Does Not See New Changes

眉间皱痕 提交于 2021-02-11 12:29:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!