Python:mysql-connector-Python查询不到新增数据

网友投稿 928 2025-03-31

查询代码

# -*- coding: utf-8 -*- import time import Mysql.connector config = { "database": "data", "username": "root", "password": "123456", "host": "127.0.0.1", "port": 3306 } connect = Mysql.connector.Connect(**config) cursor = connect.cursor(dictionary=True) while True: cursor.execute("SELECT * FROM person") result = cursor.fetchall() # fetchall() 获取所有记录 time.sleep(2) print(result) # 关闭游标和连接 cursor.close() connect.close()

1

2

3

4

5

6

7

8

9

10

Python:mysql-connector-python查询不到新增数据

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

当执行以上代码时,在MySQL数据库修改数据(增、删、改)没法获取到修改后的数据

翻阅文档10.2.35 MySQLConnection.autocommit Property发现一句话

When the autocommit is turned off, you must commit transactions when using transactional storage engines such as InnoDB or NDBCluster.

1

2

经测试,以下两个方式都能解决查询新数据的问题

配置参数autocommit=True

执行后手动commit

修改后的代码如下

# -*- coding: utf-8 -*- import time import mysql.connector config = { "database": "data", "username": "root", "password": "123456", "host": "127.0.0.1", "port": 3306, "autocommit": True } connect = mysql.connector.Connect(**config) cursor = connect.cursor(dictionary=True) while True: cursor.execute("SELECT * FROM person") result = cursor.fetchall() # 获取所有记录 time.sleep(2) print(result) print(connect.in_transaction) # 如果不commit,数据库新增、删除、修改的数据没法查询到 # connect.commit() # 关闭游标和连接 cursor.close() connect.close()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

MySQL Python

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:excel如何将每行按照时间排序(excel中怎样按时间排序)
下一篇:如何制作WPS表格的饼状图如何制作带有百分比示例的双饼状图
相关文章