Python SQLite - How to manually BEGIN and END transactions?

限于喜欢 提交于 2019-12-19 09:58:34

问题


Context

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;")

I get the following error:

OperationalError: cannot commit - no transaction is active

Which I understand is because SQLite in Python automatically opens a transaction on each modifying statement, which in this case is an INSERT.

Question:

I am trying to speed my insertion by doing one transaction per several thousand records. How can I overcome the automatic opening of transactions?


回答1:


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")



回答2:


The documentaton says:

You can control which kind of BEGIN statements sqlite3 implicitly executes (or none at all) via the isolation_level parameter to the connect() call, or via the isolation_level property of connections.

If you want autocommit mode, then set isolation_level to None.



来源:https://stackoverflow.com/questions/24374242/python-sqlite-how-to-manually-begin-and-end-transactions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!