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.

6 min readUpdated 2026-11-30
In This Lesson
  • 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:

text
FastAPI Route Handler ─▶ Pydantic Validation ─▶ Repository ─▶ sqlite3 Connection ─▶ app.db

SQLite 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):

python
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
    )
""")
SQLite Disables Foreign Keys & WAL Concurrency by Default

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

Why ? Placeholders Block 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:

python
# 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):

python
# 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.

Watch the 1-Item Tuple Comma & Dynamic Column Names
  1. In Python, ("maya@example.com") without a trailing comma is just a str, NOT a tuple—so sqlite3 treats each character as a separate placeholder and raises ProgrammingError: Incorrect number of bindings supplied. Always write (email,) or [email].
  2. ? 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:
python
ALLOWED_SORTS = {"hours": "hours DESC", "title": "title ASC"}
order_clause = ALLOWED_SORTS.get(sort_param, "id ASC")

SQLite (sqlite3) vs PostgreSQL (psycopg)

FeatureSQLite (sqlite3)PostgreSQL (psycopg)
Placeholder syntax? ((email,))%s ((email,))
Auto-increment keyINTEGER PRIMARY KEY AUTOINCREMENTGENERATED ALWAYS AS IDENTITY / SERIAL
Deployment modelEmbedded single file (app.db)Client-server daemon + connection pool
Best suited forLocal apps, single-node APIs, fast testsMulti-worker/multi-container production APIs

4. Fetching One vs Many Rows

  • .fetchone() → returns a single sqlite3.Row or None if no row matched.
  • .fetchall() → returns a list[sqlite3.Row] of all matching rows (always check limit so large tables don't exhaust RAM).
  • cursor.lastrowid → after an INSERT, gives you the newly generated PRIMARY KEY id.
  • cursor.rowcount → after an UPDATE or DELETE, tells you how many rows were actually modified (0 means nothing matched—great for raising 404!).

Try It Yourself in the Playground

Pyodide includes full sqlite3 support right in your browser! Run real SQL tables, inserts, and parameterized lookups below:

Python 3Try It Live: Python sqlite3 & Parameterized Queries
Output

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

Check Your Understanding

Why does passing (user_input,) to conn.execute('SELECT * FROM users WHERE name = ?', (user_input,)) prevent SQL injection?

Check Your Understanding

What happens if you pass ('maya@example.com') without a comma inside conn.execute('SELECT ... WHERE email = ?', ('maya@example.com'))?