我對 python 的內置模塊 sqlite3 的行為感到困惑。無論我是否注釋掉/在包含提交陳述句的行中,以下代碼都會列印出插入的資料。這個怎么可能?
我閱讀 python 檔案的理解是,雖然 sqlite3 的底層 C 庫默認啟用了自動提交,但 python 系結沒有。相反,我必須添加isolation_level=None到 connect() 呼叫才能啟用自動提交。我問這個是因為我想關閉自動提交并且找不到這樣做的方法。
我的 Python 版本是 3.9.2,由于 sqlite3 是內置模塊,所以我認為模塊版本也是 3.9.2。
import sqlite3
import os
if os.path.exists("dummy.db"):
os.system('rm dummy.db')
assert not os.path.exists("dummy.db") #ensure dummy.db is a new db every run
# Write
c = sqlite3.connect("dummy.db")
ddl = '''--sql
CREATE TABLE foo_table (foo INTEGER, bar INTEGER, foobar INTEGER);
'''
c.execute(ddl)
ddl = '''--sql
INSERT INTO foo_table VALUES(1,2,3);
'''
c.execute(ddl)
#c.commit()
c.close()
# Read
c = sqlite3.connect("dummy.db")
ddl = 'SELECT * FROM foo_table'
for row in c.execute(ddl):
print(row)
輸出
>>(1, 2, 3)
uj5u.com熱心網友回復:
SQLite 中帶有“--sql”行的命令以腳本模式運行,默認情況下似乎是自動提交,而不是執行單個 SQL 命令,默認情況下使用手動提交模式進行插入、更新、洗掉等。如果更改從命令--sql到標準 SQL 命令,然后插入被推遲,直到執行顯式提交。
con = sqlite3.connect("dummy.db")
cursor = con.cursor()
# auto-commit mode for CREATE/ALTER/DROP
cursor.execute('CREATE TABLE foo_table (foo INTEGER, bar INTEGER, foobar INTEGER)')
# Manual commit mode (the default) for INSERT, UPDATE, DELETE
cursor.execute('INSERT INTO foo_table VALUES(1,2,3)')
# uncomment commit below and the row will be inserted
#con.commit()
con.close()
# Read
con = sqlite3.connect("dummy.db")
cursor = con.cursor()
cursor.execute('SELECT * FROM foo_table')
result = cursor.fetchall()
print("rows=", len(result), sep='')
for row in result:
print(row)
輸出:
rows=0
如果您希望為 SQL 命令啟用自動提交模式,則將isolation_level 設定為None。
con = sqlite3.connect("dummy.db", isolation_level=None)
輸出:
rows=1
(1, 2, 3)
對于更細粒度的控制,您可以使用帶有 BEGIN、COMMIT 和 ROLLBACK 命令的transactions 。如果呼叫回滾或只是關閉連接,則不會提交插入。
cursor.execute("begin")
cursor.execute("INSERT...")
cursor.execute("rollback")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434084.html
