SQL injection in Python: why f-strings break your queries (with sqlite3)
How building SQL with f-strings crashes on a name like 's-Hertogenbosch and lets attackers rewrite your query, and how parameterised queries in sqlite3 fix both.
SQL injection has been on every "top security risks" list for over twenty years, and it's still written every day, usually by someone who just wanted a quick query to work. Here's how it happens in Python, and the one habit that prevents it.
A query that looks fine
def events_at(conn, location):
sql = f"SELECT parcel_id, status FROM events WHERE location = '{location}'"
return conn.execute(sql).fetchall()It works for Hamburg. It works in every test. Then someone searches for the Dutch city
's-Hertogenbosch:
SELECT parcel_id, status FROM events WHERE location = ''s-Hertogenbosch'The apostrophe ends the string early, and SQLite raises OperationalError. That's the friendly
version of this bug. (It's the exact ticket you fix in the tracking service on the
Python Developer career path.)
The unfriendly version
Now someone types this into the search box on purpose:
x' OR '1'='1The query becomes:
SELECT parcel_id, status FROM events WHERE location = 'x' OR '1'='1'That condition is true for every row: the search returns every parcel in the database. With a bit more effort, attackers read other tables, or change and delete data. The input stopped being data and became code.
The fix: parameters
def events_at(conn, location):
return conn.execute(
"SELECT parcel_id, status FROM events WHERE location = ?",
(location,),
).fetchall()The ? is a placeholder. The SQL text and the value travel to the database separately, so
whatever is in location, apostrophes and all, can only ever be compared as a value. Both bugs
are gone at once.
Details that trip people up:
- The parameters are a tuple:
(location,)with a trailing comma.(location)is just a string in brackets, and SQLite will treat each character as a separate parameter. - Named placeholders work too:
WHERE location = :locwith{"loc": location}. executemany(sql, rows)inserts many rows with the same safety.- Other drivers use other placeholders (
%sin psycopg), but the rule is the same: pass values separately, never format them in.
What parameters can't do
Placeholders stand for values only. You can't parameterise a table name, a column name, or
ASC / DESC. If those must vary, choose from a fixed list in your code:
SORTABLE = {"time": "at", "parcel": "parcel_id"}
column = SORTABLE.get(sort_key, "at")
sql = f"SELECT * FROM events ORDER BY {column}" # safe: column comes from our dictEscaping is not the fix
"Just replace ' with ''" covers one case and misses others (encodings, backslashes, numeric
contexts). Parameters are simpler and correct. If you see hand-made escaping in a review, flag it.
Our code review checklist has a security section for exactly this.
Defence in depth
Parameters stop injection. Good habits limit the damage of everything else: validate input at the edges, give the app's database user only the permissions it needs, and close connections reliably with context managers.
Questions and answers
- How do I prevent SQL injection in Python?
- Never put values into SQL with f-strings, % or +. Pass them as parameters: conn.execute('SELECT * FROM t WHERE city = ?', (city,)). The database driver sends the value separately from the SQL, so it can never change the query's meaning.
- Can I use parameters for table or column names?
- No, placeholders only work for values. If a table or column name must vary, pick it from a fixed allow-list in your code, never directly from user input.
Practise it
Read next
- Validating input: check once at the boundary, then trust your types
Where to validate data, how to report every problem at once with field paths, and how to write error messages people can act on. With examples in Python.
- Python context managers: how with works, and how to write your own
What the with statement guarantees, __enter__ and __exit__ step by step, the contextlib shortcut, and why returning True from __exit__ silently swallows errors.
- Code review checklist for junior developers
What senior engineers look for in a code review, as a practical checklist: correctness, edge cases, tests, naming, structure and performance, with C++-specific points.