Python模块mysql-connector没有看到新的变化 [英] Python module mysql-connector does not see new changes

查看:39
本文介绍了Python模块mysql-connector没有看到新的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 mysql.connector 模块来获取python脚本中的行,但是当我使用终端更新表时,我的脚本看不到任何变化.

I use the mysql.connector module to fetch rows in a python script but when I update a table using the terminal, my script doesen't see any changes.

我的代码是这样的:

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())

第一次,它总是读取正确的值,但是第二次,即使我更新了数据库,它也看不到更改.

The first time it always reads the correct values but at the second time it does not see changes even when I have update my database.

我尝试了这种解决方案,但仍然无法正常工作:

I tried this solutions but it still did not work:

  • 我尝试使用 mysql.connector 模块
  • 更新数据库
  • 我尝试安装一些旧版本
  • 我尝试使用root用户

推荐答案

使用时执行 DML ,例如 update ,删除等.执行该操作后必须提交游标否则,您的操作将无法保存.一段时间内有提交游标的用例

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

  • 由于电力问题
  • 原子性事务将回滚或稍后提交

喜欢

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

或者您可以在与数据库连接时传递 autocommit = True ,它也会起作用,它也是全局配置,将在一定时间间隔内提交喜欢

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()

这篇关于Python模块mysql-connector没有看到新的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆