如何使用 Python 设置 SQLite 隔离级别

How to set SQLite isolation levels, using Python

我知道(或者至少,我认为我知道),在处理事务时,标准中有四个隔离级别:

READ UNCOMMITTED - will allow everything
READ COMMITTED - will not allow dirty reads 
REPEATABLE READ - will not allow dirty, non-repearable reads   
SERIALIZABLE - will not allow dirty, non-repearable, phantom reads

我知道,例如,在处理 MySQL 时,我可以这样做:

cursor = db.cursor()
cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED")

或者,如果我正在处理 Postgre,我可以这样做:

db.set_isolation_level(3) # corresponds to SERIALIZABLE

所以,我想知道,在处理 SQLite 时,我是否可以做类似的事情。我只看过:

db.isolation_level = None

但我不确定这意味着什么以及如何设置其他隔离级别(如果它们存在于 SQLite 的上下文中)。谢谢!

sqlite中有PRAGMA statements个。看来你可以这样做:

db.execute("PRAGMA read_uncommitted = true;");

扩展 Martin 的回答...

SQLite中的所有事务都是SERIALIZABLE,因为SQLite通过数据库范围的读写锁来控制并发,所以一次只能有一个写入者。

例外情况是如果您设置了 shared cache mode between two or more connections in the same process and enabled the read_uncommited pragma,在这种情况下,这些连接可以在 READ UNCOMMITED 模式下运行(但共享缓存之外的连接将像往常一样阻止它们)。

根据文档,SQLite 支持 WAL Mode(实际上,SNAPSHOT 隔离级别)。

查看有关 isolation in SQLite 的详细信息。