SQLite Connection With Context Manager
Open a SQLite connection as a context manager so transactions commit on success and roll back on error, and the connection always closes.
Code
import sqlite3
from contextlib import closing
from typing import List, Tuple
def fetch_users(db_path: str) -> List[Tuple[int, str]]:
with closing(sqlite3.connect(db_path)) as connection:
connection.row_factory = sqlite3.Row
with connection:
cursor = connection.execute(
"SELECT id, email FROM users WHERE active = ?", (1,)
)
rows = cursor.fetchall()
return [(row["id"], row["email"]) for row in rows]
def create_schema(connection: sqlite3.Connection) -> None:
connection.execute(
"CREATE TABLE IF NOT EXISTS users ("
"id INTEGER PRIMARY KEY, email TEXT NOT NULL, active INTEGER DEFAULT 0)"
)Report a problem with this exampleOpens a pre-filled issue on GitHub.