Python SQLite - 如何手动开始和结束事务? [英] Python SQLite - How to manually BEGIN and END transactions?
本文介绍了Python SQLite - 如何手动开始和结束事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
背景
所以我想弄清楚在 Python 中使用 SQLite 时如何正确覆盖自动事务.当我尝试运行
So I am trying to figure out how to properly override the auto-transaction when using SQLite in Python. When I try and run
cursor.execute("BEGIN;")
.....an assortment of insert statements...
cursor.execute("END;")
我收到以下错误:
OperationalError: cannot commit - no transaction is active
我的理解是因为 Python 中的 SQLite 会自动在每个修改语句上打开一个事务,在这种情况下是一个 INSERT.
Which I understand is because SQLite in Python automatically opens a transaction on each modifying statement, which in this case is an INSERT.
问题:
我试图通过每几千条记录进行一次交易来加快插入速度.如何克服自动开启交易的问题?
I am trying to speed my insertion by doing one transaction per several thousand records. How can I overcome the automatic opening of transactions?
推荐答案
As @CL.说你必须将隔离级别设置为 None
.代码示例:
As @CL. said you have to set isolation level to None
. Code example:
s = sqlite3.connect("./data.db")
s.isolation_level = None
try:
c = s.cursor()
c.execute("begin")
...
c.execute("commit")
except:
c.execute("rollback")
这篇关于Python SQLite - 如何手动开始和结束事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文