Python SQLite-如何手动开始和结束事务?
问题内容:
语境
因此,我试图找出在Python中使用SQLite时如何正确覆盖自动交易。当我尝试运行
cursor.execute("BEGIN;")
.....an assortment of insert statements...
cursor.execute("END;")
我收到以下错误:
OperationalError: cannot commit - no transaction is active
据我了解,是因为Python中的SQLite自动在每个修改语句(在本例中为INSERT)上打开一个事务。
题:
我正在尝试通过每几千条记录执行一次事务来加快插入速度。 我该如何克服交易的自动开启?
问题答案:
作为@CL。表示您必须将隔离级别设置为None
。代码示例:
s = sqlite3.connect("./data.db")
s.isolation_level = None
try:
c = s.cursor()
c.execute("begin")
...
c.execute("commit")
except:
c.execute("rollback")