来自 Python3 的 sqlite3 模块中的自动提交问题

Problems with autocommit in sqlite3 module from Python3

我无法关闭给定数据库连接中的自动提交模式。根据我从 sqlite3 模块文档中了解到的内容,下面的 python 代码不应引发任何 AssertionError 异常,但它确实会引发。

table "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 块结束后所有内容都将自动处理。

这意味着提交任何剩余的未结交易。

看看这个文档: 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: