On this page
  1. Python sqlite3 Patterns
  2. Contents
  3. Safe Connection Factory, sqlite3.Row & Parameterized Queries
  4. Online Backups (con.backup())

Python sqlite3 Patterns

Prev: JSON, FTS5 & Generated Indexes | Up: sqlite3 | Next: postgresql
Rel: python3 sqlite3, WAL Mode & PRAGMA Tuning, Python Web APIs
Ref: docs.python.org — sqlite3
Tags: #public #databases #sqlite3 #python3


Contents


Safe Connection Factory, sqlite3.Row & Parameterized Queries

Always pass values as ? or :named parameters (never f-strings) to prevent SQL injection, and use with con: to auto-commit on success or roll back on exceptions:

import sqlite3

def open_db(path: str = ":memory:") -> sqlite3.Connection:
    con = sqlite3.connect(path)
    con.row_factory = sqlite3.Row
    con.execute("PRAGMA foreign_keys = ON")
    con.execute("PRAGMA busy_timeout = 5000")
    return con

con = open_db()
with con:
    con.execute("CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT NOT NULL)")
    con.execute("INSERT INTO notes (title) VALUES (:title)", {"title": "SQLite3 Guide"})

row = con.execute("SELECT id, title FROM notes WHERE id = ?", (1,)).fetchone()
print(dict(row))  # {'id': 1, 'title': 'SQLite3 Guide'}
con.close()

Online Backups (con.backup())

Never copy a live WAL-mode SQLite file with cp/shutil.copy while writers are active. Use SQLite's built-in con.backup(dst) API for safe, consistent online snapshots:

import sqlite3

src = sqlite3.connect(":memory:")
src.execute("CREATE TABLE kv (k TEXT PRIMARY KEY, v TEXT)")
src.execute("INSERT INTO kv VALUES ('env', 'prod')")
src.commit()

dst = sqlite3.connect(":memory:")
src.backup(dst)
print(dst.execute("SELECT * FROM kv").fetchall())  # [('env', 'prod')]

Linked from

Related notes