I read in the docs :
我在文檔中讀到:
...since transactions start when a cursor execute a query, but end when COMMIT or ROLLBACK is executed by the Connection object.
...因為事務在游標執行查詢時開始,但在Connection對象執行COMMIT或ROLLBACK時結束。
import MySQLdb
db = MySQLdb.connect(user="root", db="test")
c = db.cursor()
c.execute("SELECT * FROM books")
print c.fetchall()
I suspect that MySQLdb starts a transaction even on queries that do not modify data (like SELECT), because it is difficult to know if a query only reads data and doesn't write it.
我懷疑MySQLdb甚至在不修改數據的查詢(如SELECT)上啟動事務,因為很難知道查詢是否只讀取數據而不寫入數據。
cursor.commit()
after every query, to be sure that no table is locked?Thank you
謝謝
3
Yes, a SELECT
statement is like other so the transaction starts.
是的,SELECT語句與其他語句一樣,因此事務開始。
If you want to avoid this, you could do something like that:
如果你想避免這種情況,你可以這樣做:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM books ;
COMMIT ;
In detail:
詳細:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
says that the following instruction could read the rows that have been modified but that haven't received a COMMIT
yet. That kind of transaction dind't get exclusive locks.
表示以下指令可以讀取已修改但尚未收到COMMIT的行。這種交易不會得到獨家鎖。
The second part SELECT * FROM books ;
is obviously a SQL statement
and the third part COMMIT ;
ends the transaction and make it "permanent". In that case no writes are done, so the COMMIT
is used only to end the transaction and
第二部分SELECT * FROM books;顯然是一個SQL語句和第三部分COMMIT;結束交易並使其“永久”。在這種情況下,沒有寫入,因此COMMIT僅用於結束事務和
2
it is true,
but it as well automatically commits after each query, because mysql clients start with
autocommit=1
by default
這是真的,但它也會在每次查詢后自動提交,因為mysql客戶端默認以autocommit = 1開頭
you should not, since SELECT
does not hold any locks after the statement is executed. In practice, explicit commits might even cause a significant slow down.
你不應該,因為SELECT在執行語句后沒有持有任何鎖。在實踐中,顯式提交甚至可能導致顯着減速。
Just might be useful: Why connection in Python's DB-API does not have "begin" operation?
可能有用:為什么Python的DB-API中的連接沒有“開始”操作?
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/01/12/72559c22362524346a2456c2934ef1bc.html。