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
row_factory = sqlite3.Rowenables name access.row['name']reads a column by its label.- Aggregates like
MAXcome back as named columns.
Keywords and builtins used here
forprint
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.
Step 2 of 3 in Databases, step 15 of 41 in Domain tools.