SQL injection
SQL injection is the bug where untrusted text is concatenated into a query and then executed as SQL. A username of '; drop table orders;-- becomes part of the program. Bound parameters prevent it.
Detailed Explanation
The database cannot tell data from code once they are in one string. f"select * from users where name = '{name}'" gives the attacker the name channel. The fix is a parameterised statement: execute("select * from users where name = ?", (name,)). The driver sends the SQL and the value separately. The value cannot close a quote and start a new statement.
ORMs parameterise when you write filter(name=name) or where(User.name == name). They do not when you write raw(f"..."), extra(where=[name]), or order_by(user_input) if that input is a column name. Identifiers (columns, tables, ASC/DESC) cannot be bound as values. Allowlist them: if sort not in {"cents", "id"}: raise ....
LIKE wildcards (%, _) in user input are not injection in the SQL-syntax sense, but they can turn a search into a full scan. Escape them if % should be literal.
Defence is not sanitising quotes by hand. Hand-rolled escaping misses encodings, comments, and driver differences. Use the driver's parameters. Then run a linter or grep for execute(f and .format( on SQL strings in review.
Read-only database roles and least privilege limit the blast of a missed query. They do not make injection acceptable. Stored procedures are still injectable if they concatenate inside the procedure.
Tests: pass a string with a quote and a comment and assert you get zero rows or a clean error, not a 500 from broken SQL, and not a dropped table.
Code Examples
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("create table users (name text)")
conn.execute("insert into users values ('ada')")
name = "ada' OR '1'='1"
# Injected: would return every row
# conn.execute(f"select name from users where name = '{name}'")
row = conn.execute(
"select name from users where name = ?",
(name,),
).fetchone()
print(row) # None, the literal string was not a matchALLOWED = {"cents", "id"}
def order_clause(sort: str) -> str:
if sort not in ALLOWED:
raise ValueError("bad sort")
return sortCommon Gotchas
f-strings, `%`, or `+` to build SQL
this is the bug. Parameters only.
Binding a column name
`order by ?` sorts by a constant, or the driver rejects it. Allowlist identifiers.
ORM `raw()` is not automatically safe
you still pass params as a separate argument.
A WAF is a backup, not the fix
fix the query.