Problems with autocommit in sqlite3 module from Python3

我的梦境 提交于 2019-12-06 14:23:33

问题


I'm having trouble turning off the auto-commit mode in a given database connection. According to what I understood from the sqlite3 module documentation, the python code bellow should not raise any AssertionError exception, but it does.

The table "nomes" already exists in the database and contains the column "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 documentation here: 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.

What am I missing here?


回答1:


Independently of the isolation_level you use, using the with statement means everything will be handled automatically after the with block is ended.

That means commiting any remaining open transactions.

Take a look at this documentation: 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:



来源:https://stackoverflow.com/questions/47225583/problems-with-autocommit-in-sqlite3-module-from-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!