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

标签 python python-3.x sqlite autocommit

我在关闭给定数据库连接中的自动提交模式时遇到问题。根据我从 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/

相关文章:

python - "except Foo as bar"导致 "bar"从范围中删除

Python:如何使用 new .format() 输出小数点后两位数字的浮点值?

c# - Entity Framework 父 -> 子链接和外键约束失败错误

python - 连接到 GPIO PI 的旋转拨号盘

Python + cx_Oracle : Unable to acquire Oracle environment handle

Python 使用正则表达式替换

python - flask session : always getting new sessions on requests, request.cookies 始终为空

python - 将突出显示的文本复制到剪贴板,然后使用剪贴板将其附加到列表

python - 无法使用正则表达式解析sqlite查询

php - 在 PHPUnit 中的内存 SQLITE 数据库中模拟数据