我在关闭给定数据库连接中的自动提交模式时遇到问题。根据我从 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
Get or set the current isolation level. None for autocommit mode or one of “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”. See section Controlling Transactions for a more detailed explanation.
我在这里缺少什么?
最佳答案
独立于isolation_level
您使用,使用 with
语句意味着 with
之后的所有事情都将自动处理区 block 结束。
这意味着提交任何剩余的未完成事务。
看看这个文档: https://docs.python.org/2/library/sqlite3.html#using-the-connection-as-a-context-manager
Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transaction is rolled back; otherwise, the transaction is committed:
关于python - Python3 的 sqlite3 模块中自动提交的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47225583/