On this page
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
- tuts/databases/sqlite3 Linked here; links to this page; shared tags: #databases
- tuts/databases/sqlite3/json_fts5_and_extensions Linked here; links to this page; shared tags: #databases
- tuts/databases/sqlite3/wal_mode_and_pragmas Linked here; links to this page; shared tags: #databases
- tuts/databases/postgresql Linked here; shared tags: #databases
- tuts/databases/sql/dml_and_querying links to this page; shared tags: #databases
- tuts/databases/sql/query_execution_lifecycle links to this page; shared tags: #databases
- tuts/python3/stdlib_module/sqlite3 Linked here
- tuts/python3/tutorials/popular_application_domains/web_development_and_apis Linked here
- tuts/databases shared tags: #databases
- tuts/databases/design_patterns shared tags: #databases