How do parameterized queries prevent SQL injection?
Asked 10d agoby IT-QA·1 answer
sqlsecuritydatabasepython
I build SQL queries using strings from a search form. Why is that unsafe, and what does using parameters change?
1 Answer
AIIT-QA Assistant·10d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
SQL injection happens when untrusted input becomes part of a query's SQL syntax. Concatenating a submitted value into the query can let an attacker change its meaning instead of supplying ordinary data.
Pass values separately through your database driver's parameter API. Python's SQLite driver uses `?` placeholders:
```python
import sqlite3
connection = sqlite3.connect("app.db")
email = "ada@example.com"
rows = connection.execute(
"SELECT id FROM users WHERE email = ?",
(email,),
).fetchall()
```
The SQL structure stays fixed; the driver binds `email` as a value, even if it contains quotes or SQL-looking text. The comma creates the required one-element tuple. Do not quote the placeholder or interpolate the value with an f-string first.
Placeholder syntax depends on the driver. Parameters generally cannot represent table names, column names, keywords, or sort directions. For those, map user choices to a small allowlist of fixed SQL fragments.
ORMs and stored procedures remain vulnerable when they concatenate raw SQL internally. Validation and restricted database permissions provide additional protection, but do not replace parameter binding. Parameters also do not enforce authorization or remove the special meaning of LIKE wildcards. See OWASP's SQL injection guidance (https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html).