![](/img/trans.png)
[英]MySQL-python connection does not see changes to database made on another connection even after change is committed
[英]how can Python see changes made to MariaDB by another client?
在Windows計算機上,我在MariaDB(10.3.7)上有一個非常簡單的數據庫,與mysql-connector-python-rf(2.2.2)連接。
我還使用2個HeidiSQL工作台實例連接到數據庫。
當使用其中一個工作台在數據表中添加或刪除行時,可以立即在另一個工作台中使用SELECT語句訪問更改的數據。 我的結論是:第一個工作台已經對數據庫進行了更改。
但是,看到Python中的更改似乎更加復雜。 我必須在查詢之前添加commit()
才能查看更改:
config = {'user' : 'some_user',
'password': 'some_password',
'host' : '127.0.0.1',
'database': 'some_database',
'raise_on_warnings': True,
}
db = mysql.connector.connect(**config)
# wait some to make changes to the database using the HeidiSQL workbenches
db.commit() # even though Python has not changed anything which needs to be
# committed, this seems necessary to re-read the db to catch
# the changes that were committed by the other clients
cursor = db.cursor()
cursor.execute('some_SQL_query')
for result in cursor:
do_something_with(result)
cursor.close()
到目前為止,我認為commit()
用於提交Python要對數據庫進行的更改。
說commit()
還可以讀取自上次connect()
以來其他客戶端所做的更改,是否正確? 這是錯誤/不便還是功能?
還是我想念的其他事情在這里?
正如@brunodesthuilliers指出的那樣,答案似乎在隔離級別。 Python的默認值似乎是REPEATABLE READ
。 為了始終讀取最新的提交,必須更改事務的隔離級別,例如更改為READ COMMITTED
。
config = {'user' : 'some_user',
'password': 'some_password',
'host' : '127.0.0.1',
'database': 'some_database',
'raise_on_warnings': True,
}
db = mysql.connector.connect(**config)
cursor = db.cursor()
cursor.execute('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;')
cursor.close()
# wait some to make changes to the database using the HeidiSQL workbenches
cursor = db.cursor()
cursor.execute('some_SQL_query') # will now read the last committed data
for result in cursor:
do_something_with(result)
cursor.close()
寫 后線程編寫發出COMMIT
。 在讀取線程中執行COMMIT
無效。
除非您需要讀者看到未完成的更改在發生,否則我不會更改“隔離級別”。 通常這不是必需的。
因此, 作者在完成某些工作單元后應立即發出COMMIT
。 那可能是一個INSERT
; 這可能是一個漫長而復雜的操作組合。 一個簡單的例子是經典的“資金轉移:
BEGIN;
UPDATE accounts SET balance = balance + 100 WHERE id = 123; -- my account
UPDATE accounts SET balance = balance - 100 WHERE id = 432; -- your account
COMMIT;
對於誠信accounts
,你希望兩個UPDATEs
要么發生,也不會,即使系統在中間崩潰。 而且您不希望任何其他線程在讀取中間數據時看到balance
不一致。
另一種表達方式: 作者負責說“我完成了”(通過調用commit
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.