How do you prevent SQL injection?
Instruction: Explain parameterized queries, allowlisted identifiers, and why input validation alone is insufficient.
Context: Prepare a practical SQL injection answer using bound parameters and a safe Python example.
Updated
Example Answer
I use parameterized queries so user input is passed as data, rather than becoming part of the SQL statement. I also validate inputs for the application’s rules and give the database account only the permissions it needs. If users choose a sort column or table name, I map that choice to a fixed allowlist because value placeholders do not bind identifiers.
Small example
Runnable with Python’s standard-library sqlite3 module:
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (user_id INTEGER, email TEXT)")
con.execute("INSERT INTO users VALUES (?, ?)", (1, "[email protected]"))
email = "[email protected]"
rows = con.execute(
"SELECT user_id FROM users WHERE email = ?", (email,)
).fetchall()
assert rows == [(1,)]
con.close()
Use your driver’s placeholder syntax. Do not build SQL by concatenating user input or formatting it into an f-string. Validation, escaping, and stored procedures are not substitutes for safe query construction.