typestar

SQLite row access in Python

Reading query results by column name.

import sqlite3

conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE users (name TEXT, score INTEGER)")
conn.executemany("INSERT INTO users VALUES(?, ?)",
                 [("ada", 95), ("grace", 88)])

for row in conn.execute("SELECT name, score FROM users ORDER BY score DESC"):
    print(f"{row['name']}: {row['score']}")

top = conn.execute("SELECT MAX(score) AS best FROM users").fetchone()
best = top["best"]
conn.close()

How it works

  1. row_factory = sqlite3.Row enables name access.
  2. row['name'] reads a column by its label.
  3. Aggregates like MAX come back as named columns.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
446
Tokens
115
Three-star pace
105 tpm

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

Type this snippet

Step 2 of 3 in Databases, step 15 of 41 in Domain tools.

← Previous Next →