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)"
)Inside the snippet
SQLite Connection With Context Manager keeps everything in the functions fetch_users and create_schema.
The import line is the dependency contract: closing, List, Tuple come from sqlite3 and nothing else.
A fresh value is allocated for the result; the arguments stay untouched.
Points of care
- Plan for an install step:
sqlite3is a real dependency, resolved by the package manager.
Putting it to use
Signature: def fetch_users(db_path: str) -> List[Tuple[int, str]]
The surface worth importing is fetch_users; the helpers around it are private to the snippet.
Core lines
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)"
)
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()
Interactive Tools for This Topic
DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Does `fetch_users` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Are there third-party dependencies?
- `sqlite3` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.