Python:mysql-connector-Python查詢不到新增數據
查詢代碼
# -*- 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
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小時內刪除侵權內容。