Python · Module 10 · Lesson 11 min read

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

  1. conn = sqlite3.connect("app.db") opens the database (the file is created if missing).
  2. conn.execute(sql, params) runs a query.
  3. conn.commit() saves changes. with conn: commits automatically, or rolls back on error.
  4. cur.fetchone() / cur.fetchall() read results.
  5. conn.close() closes it.

Always use placeholders 🛡️

Python
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.Row lets 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

SQL
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()