我无法在给定的数据库连接中关闭自动提交模式。根据我从sqlite3模块文档中所理解的,下面的python代码不应该引发任何AssertionError异常,但确实如此。
表" nomes"已经存在于数据库中并包含列" Nome"
import sqlite3
_PATH_DB = '/rhome/FNORO/tabelao/sofia.sqlite' # path to database
_ISOLATION_LEVEL = "EXCLUSIVE"
_TEST_NAME = "TEST1"
# delete name from database
with sqlite3.connect(_PATH_DB, isolation_level = _ISOLATION_LEVEL) as conn:
query = 'DELETE FROM nomes WHERE nome = "{}"'.format(_TEST_NAME)
conn.execute(query)
conn.commit()
# insert name _TEST_NAME without executing conn.commit()
with sqlite3.connect(_PATH_DB, isolation_level = _ISOLATION_LEVEL) as conn:
query = 'INSERT INTO nomes(nome) VALUES("{}")'.format(_TEST_NAME)
conn.execute(query)
# check if name already existis
with sqlite3.connect(_PATH_DB, isolation_level = _ISOLATION_LEVEL) as conn:
query = 'SELECT nome FROM nomes WHERE nome = "{}"'.format(_TEST_NAME)
res = conn.execute(query).fetchall()
assert (res == [])
此处的Sqlite3文档:https://docs.python.org/2/library/sqlite3.html#connection-objects
isolation_level
获取或设置当前隔离级别。无自动提交模式或“DEFERRED”,“IMMEDIATE”或“EXCLUSIVE”之一。有关更详细的说明,请参阅控制事务部分。
我在这里缺少什么?
答案 0 :(得分:0)
独立于您使用的isolation_level
,使用with
语句表示在with
块结束后将自动处理所有内容。
这意味着提交任何剩余的未结交易。
看一下这个文档: https://docs.python.org/2/library/sqlite3.html#using-the-connection-as-a-context-manager
连接对象可以自动用作上下文管理器 提交或回滚事务。如果发生例外,则 交易回滚;否则,交易已经提交: