Full answer
python
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (name TEXT, is_admin INTEGER)")
con.executemany("INSERT INTO users VALUES (?, ?)", [("asha", 1), ("ben", 0)])
user_input = "nobody' OR '1'='1"
unsafe = f"SELECT name FROM users WHERE name = '{user_input}'"
print("unsafe:", con.execute(unsafe).fetchall())
print("safe: ", con.execute("SELECT name FROM users WHERE name = ?", (user_input,)).fetchall())
def sorted_users(column):
if column not in {"name", "is_admin"}:
raise ValueError("bad sort column")
return con.execute(f"SELECT name FROM users ORDER BY {column}").fetchall()
print(sorted_users("name"))
try:
sorted_users("name; DROP TABLE users")
except ValueError as e:
print("ValueError:", e)Output:
text
unsafe: [('asha',), ('ben',)]
safe: []
[('asha',), ('ben',)]
ValueError: bad sort columnThe crafted input closes the quote and adds OR '1'='1', so the unsafe query returns every user. With a placeholder, the whole input is compared as a literal name and nothing matches. Sort columns cannot be passed as parameters, so the allow-list check is the safe way to build that part of the SQL. ORMs and query builders parameterise for you, but raw SQL fragments inside them carry the same risk.
python
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (name TEXT, is_admin INTEGER)")
con.executemany("INSERT INTO users VALUES (?, ?)", [("asha", 1), ("ben", 0)])
user_input = "nobody' OR '1'='1"
unsafe = f"SELECT name FROM users WHERE name = '{user_input}'"
print("unsafe:", con.execute(unsafe).fetchall())
print("safe: ", con.execute("SELECT name FROM users WHERE name = ?", (user_input,)).fetchall())
def sorted_users(column):
if column not in {"name", "is_admin"}:
raise ValueError("bad sort column")
return con.execute(f"SELECT name FROM users ORDER BY {column}").fetchall()
print(sorted_users("name"))
try:
sorted_users("name; DROP TABLE users")
except ValueError as e:
print("ValueError:", e)Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Never format user input into SQL
- Use ? or named placeholders
- Parameters are always data
- Allow-list identifiers
- ORM raw fragments carry the same risk
Common mistakes
- Escaping quotes by hand
- Parameterising values but formatting column names from input
Follow-ups
- How does executemany help with bulk inserts?
- What other injection types exist?
Tips
- Show the malicious input