typestar

sqlite3, further in Python

Row factories, parameter binding and the transaction context manager.

import sqlite3

conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE runs (lang TEXT, tpm INTEGER)")

with conn:
    conn.executemany("INSERT INTO runs VALUES (?, ?)",
                     [("python", 104), ("rust", 98)])

row = conn.execute("SELECT * FROM runs WHERE lang = ?", ("rust",)).fetchone()
print(dict(row), row["tpm"])

try:
    with conn:
        conn.execute("INSERT INTO runs VALUES (?, ?)", ("bad", 1))
        raise ValueError("changed my mind")
except ValueError:
    pass
print(conn.execute("SELECT COUNT(*) FROM runs").fetchone()[0])

How it works

  1. row_factory = sqlite3.Row gives dict-like rows.
  2. Always bind parameters; never format SQL with f-strings.
  3. The connection as a context manager commits or rolls back.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
543
Tokens
141
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 4 of 4 in Measuring & introspecting, step 38 of 41 in Domain tools.

← Previous Next →