Python

sqlite3 with Row Factory + Context

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Stdlib sqlite3 is fine for embedded / small workloads. Use `with conn:` for automatic commit/rollback, and a row_factory so you get dicts (or namedtuples) instead of bare tuples.
Python
Raw
import sqlite3
from pathlib import Path

def connect(path: str | Path) -> sqlite3.Connection:
    conn = sqlite3.connect(path)
    conn.row_factory = sqlite3.Row              # rows behave like dicts
    conn.execute("PRAGMA foreign_keys = ON")
    return conn

with connect("app.db") as db:
    db.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
    db.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
    # The `with` block commits on success, rolls back on exception.

with connect("app.db") as db:
    for row in db.execute("SELECT id, name FROM users"):
        print(row["id"], row["name"])           # dict-style access
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.