Python Glossary Русский

all Python 3sqlite3term

sqlite3.Connection

connections and queries

An open SQLite database: it runs queries, controls transactions (commit, rollback) and is closed with close(). It is created by sqlite3.connect().

Syntax

conn = sqlite3.connect(':memory:'); with conn: conn.execute(sql, params)

By default changes sit in an open transaction and are lost unless you call commit(). A with conn: block commits on success and rolls back on an exception, but it does NOT close the connection — you still need close() (or contextlib.closing). conn.execute() is a shortcut that creates a cursor and returns it. Setting row_factory = sqlite3.Row gives access to columns by name.

Examples

import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE t(x)')
with conn:
    conn.execute('INSERT INTO t VALUES (1)')  # commit при выходе
try:
    with conn:
        conn.execute('INSERT INTO t VALUES (2)')
        raise ValueError('сбой')
except ValueError:
    pass
print(conn.execute('SELECT count(*) FROM t').fetchone()[0])  # → 1 — вторая вставка откатилась
print(conn.execute('SELECT 42').fetchone())  # → (42,) — после with соединение открыто
conn.close()
import sqlite3
conn = sqlite3.connect(':memory:')
conn.close()
try:
    conn.execute('SELECT 1')
except sqlite3.ProgrammingError as e:
    print(e)  # → Cannot operate on a closed database.

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy