SQLite with sqlite3
SQLite: a database in one file
It's built into Python (import sqlite3), needs no server, and is perfect for learning SQL, small apps and prototypes. It even runs inside most phones.
The workflow
conn = sqlite3.connect("app.db")opens the database (the file is created if missing).conn.execute(sql, params)runs a query.conn.commit()saves changes.with conn:commits automatically, or rolls back on error.cur.fetchone()/cur.fetchall()read results.conn.close()closes it.
Always use placeholders 🛡️
conn.execute("SELECT * FROM users WHERE name = ?", (name,))
Never build SQL with f-strings from user input; that allows SQL injection attacks.
Nice extras
conn.row_factory = sqlite3.Rowlets you access columns by name:row["name"].executemany()inserts many rows at once.sqlite3.connect(":memory:")creates a temporary database, which is great for tests.
▶️ Runs in the app.
Example
import sqlite3
conn = sqlite3.connect(":memory:") # use "app.db" for a real file
conn.row_factory = sqlite3.Row
with conn: # commits automatically
conn.execute("""
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
score INTEGER DEFAULT 0
)
""")
conn.executemany(
"INSERT INTO users (name, score) VALUES (?, ?)",
[("Ana", 90), ("Ben", 72), ("Cara", 85)],
)
rows = conn.execute(
"SELECT name, score FROM users WHERE score >= ? ORDER BY score DESC", (80,)
).fetchall()
for row in rows:
print(row["name"], row["score"]) # Ana 90 / Cara 85
conn.close()