2. Python + SQL Databases
Connecting Python to SQL with sqlite3 (No SQL Injection)
Query relational databases directly from Python using the built-in sqlite3 module, Row dictionary-like access, and parameterized ? placeholders that prevent SQL injection.
- Create tables, insert rows, and run SELECT queries from Python using sqlite3
- Use sqlite3.Row to read columns by name instead of fragile numeric indexes
- Prevent SQL injection completely by passing parameters via ? placeholders
In SQL & Relational Databases, you wrote queries directly inside SQL. Now let's connect Python to SQL using Python's built-in sqlite3 module!
Even if you later deploy with PostgreSQL (psycopg), the exact same architectural pattern applies: open a connection per unit of work, execute parameterized SQL, and map rows cleanly into Python objects.
1. Where the Database Sits in Backend Architecture
In a clean API, SQL queries never float around loose—they sit at the bottom of the request pipeline:
FastAPI Route Handler ─▶ Pydantic Validation ─▶ Repository ─▶ sqlite3 Connection ─▶ app.dbSQLite stores the entire database in a single file (app.db) or in RAM (:memory:), making it zero-config for local backends, CLI tools, and tests. When scaling to multiple server instances later, swapping to PostgreSQL changes the driver (? placeholders become %s) while keeping your repository structure intact.
2. Connecting, sqlite3.Row & Foreign Key Pragmas
By default, sqlite3 returns rows as plain tuples like (1, 'Maya', 'maya@example.com')—if someone adds a column in SELECT, numeric indexes (row[1]) silently break! Setting conn.row_factory = sqlite3.Row lets you access columns by name (row["email"]) or convert directly with dict(row):
import sqlite3
conn = sqlite3.connect("app.db") # Or ":memory:" for ephemeral RAM storage
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON") # Disabled by default per connection in SQLite!
conn.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
)
""")Always run conn.execute("PRAGMA foreign_keys = ON") on every new SQLite connection so invalid FOREIGN KEY IDs are rejected instead of ignored. For file-backed web APIs, also run PRAGMA journal_mode = WAL; once on startup so concurrent reads don't block while a write commits.
3. Parameterized Queries (?) vs SQL Injection
Unsafe f-string (SQL Altered!)
WHERE slug = '' OR '1'='1'
Safe Parameterized ? (Inert String)
WHERE slug = ? · data=("' OR '1'='1",)
f-strings glue user input directly into SQL syntax; ? placeholders pass user input separately as inert literal data.
NEVER build SQL queries using f-strings, %, or + concatenation with user input:
# DANGEROUS! Never do this!
# If email = "' OR '1'='1", the string alters the SQL syntax and returns EVERY row!
conn.execute(f"SELECT * FROM students WHERE email = '{email}'")Instead, always pass user values as a separate tuple or list argument using ? placeholders (%s in PostgreSQL psycopg):
# SAFE: The SQL statement is compiled first; `email` is bound strictly as literal data.
row = conn.execute(
"SELECT id, name, email FROM students WHERE email = ?",
(email,), # Notice the trailing comma for a 1-item tuple!
).fetchone()Why ? Stops Injection Completely
With string formatting, user input is pasted before SQLite parses the SQL grammar—letting quotes (') break out of the string literal and inject OR 1=1 or DROP TABLE. With ? placeholders, SQLite parses the SQL AST first and binds (email,) purely as a value leaf node, so quotes and SQL keywords inside email are harmless text.
- In Python,
("maya@example.com")without a trailing comma is just astr, NOT a tuple—sosqlite3treats each character as a separate placeholder and raisesProgrammingError: Incorrect number of bindings supplied. Always write(email,)or[email]. ?placeholders only work for values, not table/column names (ORDER BY ?sorts by a constant string!). For dynamic sorting, map user input through an explicit allowlist dict:
ALLOWED_SORTS = {"hours": "hours DESC", "title": "title ASC"}
order_clause = ALLOWED_SORTS.get(sort_param, "id ASC")SQLite (sqlite3) vs PostgreSQL (psycopg)
| Feature | SQLite (sqlite3) | PostgreSQL (psycopg) |
|---|---|---|
| Placeholder syntax | ? ((email,)) | %s ((email,)) |
| Auto-increment key | INTEGER PRIMARY KEY AUTOINCREMENT | GENERATED ALWAYS AS IDENTITY / SERIAL |
| Deployment model | Embedded single file (app.db) | Client-server daemon + connection pool |
| Best suited for | Local apps, single-node APIs, fast tests | Multi-worker/multi-container production APIs |
4. Fetching One vs Many Rows
.fetchone()→ returns a singlesqlite3.RoworNoneif no row matched..fetchall()→ returns alist[sqlite3.Row]of all matching rows (always checklimitso large tables don't exhaust RAM).cursor.lastrowid→ after anINSERT, gives you the newly generatedPRIMARY KEYid.cursor.rowcount→ after anUPDATEorDELETE, tells you how many rows were actually modified (0means nothing matched—great for raising404!).
Try It Yourself in the Playground
Pyodide includes full sqlite3 support right in your browser! Run real SQL tables, inserts, and parameterized lookups below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Insert a new course ("python-backend", "Python Backend & APIs", 16) into courses, print cur.lastrowid, and query it back by id.
Quick Checkpoints
Why does passing (user_input,) to conn.execute('SELECT * FROM users WHERE name = ?', (user_input,)) prevent SQL injection?
What happens if you pass ('maya@example.com') without a comma inside conn.execute('SELECT ... WHERE email = ?', ('maya@example.com'))?