Claude Code for sqlite3: Embedded Databases in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for sqlite3: Embedded Databases in Python
AI

Claude Code for sqlite3: Embedded Databases in Python

Published: July 12, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s sqlite3 module provides a zero-configuration embedded SQL database. import sqlite3. connect: con = sqlite3.connect("app.db"). in-memory: sqlite3.connect(":memory:"). cursor: cur = con.cursor(); cur.execute("SELECT ..."). fetchone/all: cur.fetchone(); cur.fetchall(). row_factory: con.row_factory = sqlite3.Row — access columns by name. execute context: with con: con.execute("INSERT ...") — auto-commits or rolls back. parameterized: cur.execute("SELECT * FROM t WHERE id = ?", (id_val,)) — NEVER use % or f-string. executemany: cur.executemany("INSERT INTO t VALUES (?,?)", rows). create_table: con.execute("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, ...)"). WAL mode: con.execute("PRAGMA journal_mode=WAL") — better concurrent reads. check_same_thread: sqlite3.connect("app.db", check_same_thread=False) — multi-thread. backup: con.backup(dest_con). register_adapter: sqlite3.register_adapter(type, fn). register_converter: sqlite3.register_converter("typename", fn). detect_types: sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES). create_function: con.create_function("fn_name", n_args, callable). lastrowid: cur.lastrowid. rowcount: cur.rowcount. isolation_level: sqlite3.connect("app.db", isolation_level=None) — autocommit. close: con.close(). Claude Code generates typed repository classes, migration runners, and in-memory test fixtures.

CLAUDE.md for sqlite3

## sqlite3 Stack
- Stdlib: import sqlite3
- Connect: con = sqlite3.connect("app.db"); con.row_factory = sqlite3.Row
- Query: con.execute("SELECT ... WHERE id = ?", (val,))  — ALWAYS use ? placeholders
- Write: with con: con.execute("INSERT ...") / con.executemany("INSERT ...", rows)
- WAL: con.execute("PRAGMA journal_mode=WAL")  — enable for read-heavy workloads
- Test: sqlite3.connect(":memory:")  — isolated, ephemeral database for unit tests

sqlite3 Repository Pipeline

# app/db.py — connect, Row factory, typed repository, migrations, in-memory
from __future__ import annotations

import sqlite3
import threading
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Generator, Iterable, Iterator


# ─────────────────────────────────────────────────────────────────────────────
# 1. Connection factory
# ─────────────────────────────────────────────────────────────────────────────

def open_db(
    path: str | Path = ":memory:",
    wal: bool = True,
    timeout: float = 30.0,
    row_factory: bool = True,
) -> sqlite3.Connection:
    """
    Open an SQLite connection with sensible defaults.

    Example:
        con = open_db("app.db")
        con = open_db(":memory:")   # fast test database
    """
    p   = str(path)
    con = sqlite3.connect(p, timeout=timeout, check_same_thread=False)
    if row_factory:
        con.row_factory = sqlite3.Row
    con.execute("PRAGMA foreign_keys = ON")
    if wal and p != ":memory:":
        con.execute("PRAGMA journal_mode = WAL")
    return con


@contextmanager
def db_transaction(con: sqlite3.Connection) -> Generator[sqlite3.Connection, None, None]:
    """
    Context manager that commits on success and rolls back on any exception.

    Example:
        with db_transaction(con) as c:
            c.execute("INSERT INTO orders VALUES (?,?)", (order_id, amount))
            c.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (amount, user_id))
    """
    try:
        yield con
        con.commit()
    except Exception:
        con.rollback()
        raise


@contextmanager
def temp_db() -> Generator[sqlite3.Connection, None, None]:
    """
    Yield an in-memory SQLite connection; close on exit.
    Useful for isolated test fixtures.

    Example:
        with temp_db() as con:
            setup_schema(con)
            assert count_users(con) == 0
    """
    con = open_db(":memory:")
    try:
        yield con
    finally:
        con.close()


# ─────────────────────────────────────────────────────────────────────────────
# 2. Schema migrations
# ─────────────────────────────────────────────────────────────────────────────

def get_schema_version(con: sqlite3.Connection) -> int:
    """Return current user_version pragma value."""
    row = con.execute("PRAGMA user_version").fetchone()
    return row[0] if row else 0


def set_schema_version(con: sqlite3.Connection, version: int) -> None:
    """Set user_version pragma (requires no ? placeholder)."""
    con.execute(f"PRAGMA user_version = {int(version)}")


def run_migrations(
    con: sqlite3.Connection,
    migrations: list[tuple[int, str]],
) -> int:
    """
    Run pending migrations in version order.
    Each migration is a (version, sql) tuple.
    Returns number of migrations applied.

    Example:
        MIGRATIONS = [
            (1, "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)"),
            (2, "ALTER TABLE users ADD COLUMN created_at TEXT"),
        ]
        run_migrations(con, MIGRATIONS)
    """
    current = get_schema_version(con)
    applied = 0
    for version, sql in sorted(migrations, key=lambda m: m[0]):
        if version > current:
            with db_transaction(con):
                for stmt in sql.strip().split(";"):
                    stmt = stmt.strip()
                    if stmt:
                        con.execute(stmt)
                set_schema_version(con, version)
            applied += 1
    return applied


# ─────────────────────────────────────────────────────────────────────────────
# 3. Query helpers
# ─────────────────────────────────────────────────────────────────────────────

def fetch_one(
    con: sqlite3.Connection,
    sql: str,
    params: tuple = (),
) -> sqlite3.Row | None:
    """
    Execute a SELECT and return the first row or None.

    Example:
        user = fetch_one(con, "SELECT * FROM users WHERE email = ?", (email,))
        if user:
            print(user["name"])
    """
    return con.execute(sql, params).fetchone()


def fetch_all(
    con: sqlite3.Connection,
    sql: str,
    params: tuple = (),
) -> list[sqlite3.Row]:
    """Execute a SELECT and return all rows."""
    return con.execute(sql, params).fetchall()


def fetch_scalar(
    con: sqlite3.Connection,
    sql: str,
    params: tuple = (),
    default: Any = None,
) -> Any:
    """
    Execute a SELECT and return a single scalar value.

    Example:
        count = fetch_scalar(con, "SELECT COUNT(*) FROM users WHERE active = 1")
        total = fetch_scalar(con, "SELECT SUM(amount) FROM orders WHERE user_id = ?", (uid,))
    """
    row = con.execute(sql, params).fetchone()
    return row[0] if row else default


def execute_script(con: sqlite3.Connection, sql: str) -> None:
    """
    Execute a multi-statement SQL script (e.g., a migration file).

    Example:
        execute_script(con, Path("schema.sql").read_text())
    """
    con.executescript(sql)


def iter_rows(
    con: sqlite3.Connection,
    sql: str,
    params: tuple = (),
) -> Iterator[sqlite3.Row]:
    """
    Lazily iterate query results — memory-efficient for large result sets.

    Example:
        for row in iter_rows(con, "SELECT * FROM events ORDER BY ts"):
            process(row)
    """
    return iter(con.execute(sql, params))


# ─────────────────────────────────────────────────────────────────────────────
# 4. Typed repository pattern
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class User:
    name:       str
    email:      str
    id:         int  = 0
    active:     bool = True
    created_at: str  = field(default_factory=lambda: datetime.utcnow().isoformat())


class UserRepository:
    """
    CRUD repository for the users table.

    Example:
        repo = UserRepository(con)
        uid  = repo.create(User(name="Alice", email="[email protected]"))
        user = repo.get(uid)
        repo.update(uid, active=False)
        users = repo.list_active(limit=10)
    """

    SCHEMA = """
        CREATE TABLE IF NOT EXISTS users (
            id         INTEGER PRIMARY KEY AUTOINCREMENT,
            name       TEXT    NOT NULL,
            email      TEXT    NOT NULL UNIQUE,
            active     INTEGER NOT NULL DEFAULT 1,
            created_at TEXT    NOT NULL
        )
    """

    def __init__(self, con: sqlite3.Connection) -> None:
        self.con = con
        con.execute(self.SCHEMA)
        con.commit()

    def create(self, user: User) -> int:
        """Insert user; return new row ID."""
        with db_transaction(self.con):
            cur = self.con.execute(
                "INSERT INTO users (name, email, active, created_at) VALUES (?,?,?,?)",
                (user.name, user.email, int(user.active), user.created_at),
            )
        return cur.lastrowid

    def get(self, user_id: int) -> User | None:
        """Fetch user by ID or return None."""
        row = fetch_one(self.con, "SELECT * FROM users WHERE id = ?", (user_id,))
        return self._to_user(row) if row else None

    def get_by_email(self, email: str) -> User | None:
        row = fetch_one(self.con, "SELECT * FROM users WHERE email = ?", (email,))
        return self._to_user(row) if row else None

    def update(self, user_id: int, **fields) -> bool:
        """Update specific fields; return True if row was found."""
        if not fields:
            return False
        cols = ", ".join(f"{k} = ?" for k in fields)
        vals = list(fields.values()) + [user_id]
        with db_transaction(self.con):
            cur = self.con.execute(
                f"UPDATE users SET {cols} WHERE id = ?", vals
            )
        return cur.rowcount > 0

    def delete(self, user_id: int) -> bool:
        with db_transaction(self.con):
            cur = self.con.execute("DELETE FROM users WHERE id = ?", (user_id,))
        return cur.rowcount > 0

    def list_active(self, limit: int = 100, offset: int = 0) -> list[User]:
        rows = fetch_all(
            self.con,
            "SELECT * FROM users WHERE active = 1 ORDER BY id LIMIT ? OFFSET ?",
            (limit, offset),
        )
        return [self._to_user(r) for r in rows]

    def count(self) -> int:
        return fetch_scalar(self.con, "SELECT COUNT(*) FROM users", default=0)

    def bulk_insert(self, users: Iterable[User]) -> int:
        """Bulk insert; return number of rows inserted."""
        data = [(u.name, u.email, int(u.active), u.created_at) for u in users]
        with db_transaction(self.con):
            self.con.executemany(
                "INSERT OR IGNORE INTO users (name, email, active, created_at) VALUES (?,?,?,?)",
                data,
            )
        return len(data)

    @staticmethod
    def _to_user(row: sqlite3.Row) -> User:
        return User(
            id=row["id"], name=row["name"], email=row["email"],
            active=bool(row["active"]), created_at=row["created_at"],
        )


# ─────────────────────────────────────────────────────────────────────────────
# 5. Custom adapters/converters
# ─────────────────────────────────────────────────────────────────────────────

def register_json_column(con: sqlite3.Connection | None = None) -> None:
    """
    Register JSON adapter/converter so Python dicts/lists are stored as TEXT.
    Call once at app startup.

    Example:
        register_json_column()
        con = sqlite3.connect("app.db", detect_types=sqlite3.PARSE_DECLTYPES)
        con.execute("CREATE TABLE t (data JSON)")
        con.execute("INSERT INTO t VALUES (?)", ({"key": "value"},))
        row = con.execute("SELECT data FROM t").fetchone()
        print(type(row[0]))  # dict
    """
    import json

    sqlite3.register_adapter(dict,  json.dumps)
    sqlite3.register_adapter(list,  json.dumps)
    sqlite3.register_converter("JSON", json.loads)


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== sqlite3 demo ===")

    with temp_db() as con:
        repo = UserRepository(con)

        print("\n--- create users ---")
        uid1 = repo.create(User("Alice", "[email protected]"))
        uid2 = repo.create(User("Bob",   "[email protected]"))
        uid3 = repo.create(User("Carol", "[email protected]"))
        print(f"  inserted IDs: {uid1}, {uid2}, {uid3}")
        print(f"  total count: {repo.count()}")

        print("\n--- get by ID ---")
        user = repo.get(uid1)
        print(f"  user {uid1}: name={user.name}, email={user.email}, active={user.active}")

        print("\n--- update ---")
        ok = repo.update(uid2, active=False)
        print(f"  deactivated {uid2}: {ok}")

        print("\n--- list_active ---")
        active = repo.list_active()
        print(f"  active users: {[u.name for u in active]}")

        print("\n--- bulk_insert ---")
        extras = [User(f"User{i}", f"user{i}@example.com") for i in range(5)]
        inserted = repo.bulk_insert(extras)
        print(f"  bulk inserted: {inserted}, total: {repo.count()}")

        print("\n--- raw queries ---")
        count = fetch_scalar(con, "SELECT COUNT(*) FROM users WHERE active = 1")
        print(f"  active count via scalar: {count}")

        print("\n--- iter_rows ---")
        for row in iter_rows(con, "SELECT id, name FROM users WHERE active = 1 ORDER BY id LIMIT 3"):
            print(f"  {dict(row)}")

    print("\n=== done ===")

For the sqlalchemy alternative — SQLAlchemy provides a full ORM (Object-Relational Mapper) supporting PostgreSQL, MySQL, SQLite, and more with declarative model classes, relationship mapping, lazy loading, and a query language (Core + ORM layers); stdlib sqlite3 is SQLite-only, requires manual SQL, and returns dict-like rows — use sqlalchemy for production applications needing to support multiple database backends, complex joins, or migration tooling (with Alembic), stdlib sqlite3 for embedded SQLite in apps, scripts, CLI tools, and anywhere zero-dependency lightweight storage is the requirement. For the peewee alternative — peewee is a small, expressive ORM with Model subclasses, fluent query API, and support for SQLite, PostgreSQL, and MySQL with a much smaller footprint than SQLAlchemy; stdlib sqlite3 has lower overhead and no abstractions — use peewee for projects that need ORM ergonomics without SQLAlchemy’s complexity or macOS/Linux command-line tools embedding a database, stdlib sqlite3 for scripts and utilities where adding any ORM dependency is unwanted. The Claude Skills 360 bundle includes sqlite3 skill sets covering open_db()/db_transaction()/temp_db() connection helpers, get_schema_version()/run_migrations() migration runner, fetch_one()/fetch_all()/fetch_scalar()/iter_rows() query helpers, User dataclass + UserRepository CRUD with bulk_insert(), and register_json_column() custom JSON column adapter. Start with the free tier to try embedded database and sqlite3 repository pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free