On this page
  1. sqlite3
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safe Parameterized Queries, Transactions & WAL Mode
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

sqlite3

Prev: socketserver | Up: stdlib_module | Next: sre_compile
Rel: pickle, copyreg, shelve, marshal, dbm, SQLite3 Guide, SQL
Ref: docs.python.org — sqlite3
Tags: #public #python3 #stdlib


Import

import sqlite3

Overview

Embedded, zero-server relational SQL database engine built directly into Python's standard library (DB-API 2.0). Reach for sqlite3 whenever an application needs durable, ACID-transactional structured storage, indexes, or SQL queries without operating a separate database server.

Quick Start

import sqlite3

with sqlite3.connect(":memory:") as conn:
    conn.row_factory = sqlite3.Row
    conn.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
    conn.execute("INSERT INTO items (name) VALUES (?)", ("notebook",))
    row = conn.execute("SELECT id, name FROM items WHERE name = ?", ("notebook",)).fetchone()
    assert dict(row) == {"id": 1, "name": "notebook"}

Implementation Walkthrough

1. Safe Parameterized Queries, Transactions & WAL Mode

Always use ? or :name placeholders (never f-strings) to prevent SQL injection, and enable foreign keys + WAL mode on file-backed databases:

import sqlite3
from contextlib import closing

def open_db(path: str) -> sqlite3.Connection:
    conn = sqlite3.connect(path, timeout=10.0)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys = ON")
    conn.execute("PRAGMA journal_mode = WAL")
    return conn

with closing(open_db(":memory:")) as conn:
    with conn:  # commits on success, rolls back on exception
        conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE)")
        conn.executemany(
            "INSERT INTO users (email) VALUES (?)",
            [("ada@example.org",), ("grace@example.org",)],
        )

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes