我对python的内置模块sqlite3的行为感到困惑。下面的代码输出插入的数据,不管我是否在包含commit语句的行中注释掉/。这怎么可能呢?
我从阅读python中了解到,虽然sqlite3 3的底层C库默认启用了自动提交,但是python绑定没有启用。相反,我必须添加isolation_level=None来连接()调用,以便启用自动提交。我之所以问这个问题,是因为我想关闭自动提交,却找不到这样做的方法。
我的是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)发布于 2022-02-26 15:33:35
SQLite中带有“- SQL”行的命令在脚本模式下运行,该脚本模式在默认情况下似乎是自动提交,而不是执行单个SQL命令,默认情况下使用手动提交模式进行插入、更新、删除等操作。如果将命令从--sql更改为标准的--sql命令,则插入将推迟到执行expicit。
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设置为“无”。
con = sqlite3.connect("dummy.db", isolation_level=None)输出:
rows=1
(1, 2, 3)对于更细粒度的控制,您可以使用交易记录、BEGIN、COMMIT和ROLLBACK命令。如果调用回滚或简单地关闭连接,则插入未提交。
cursor.execute("begin")
cursor.execute("INSERT...")
cursor.execute("rollback")https://stackoverflow.com/questions/71277666
复制相似问题