Web › Module 1 › Lesson 4
Prevention Techniques
Prepared statements, ORMs, input validation, and why WAFs are a seatbelt—not the engine
Visual · web_developer
The fix is separation: user input must never become SQL syntax. Parameterized queries and ORMs enforce that boundary.
Opening
Stop building SQL with string glue
Every SQLi prevention talk boils down to one idea: treat user input as data, never as code. Prepared statements (parameterized queries) send the SQL structure and the values separately—the database binds values into placeholders and cannot reinterpret them as commands. Everything else—ORMs, allowlists, WAFs—supports that core rule.
1. Prepared Statements (Primary Fix)
Safe Python example with placeholdersimport sqlite3 conn = sqlite3.connect("app.db") user = request.form["user"] # untrusted cur = conn.execute( "SELECT id FROM users WHERE username = ?", (user,), ) # The ? is a bound parameter—quotes in user cannot break out
import sqlite3
conn = sqlite3.connect("app.db")
user = request.form["user"] # untrusted
cur = conn.execute(
"SELECT id FROM users WHERE username = ?",
(user,),
)
# The ? is a bound parameter—quotes in user cannot break outUse the parameter API your driver provides (? , %s, @name)—never interpolate untrusted strings into the query text.
2. ORMs and Query Builders
ORMs (SQLAlchemy, Django ORM, Prisma)
High-level queries parameterize by default when you use their APIs—not raw SQL strings.
Raw ORM SQL
Still dangerous if you embed f-strings; use bound parameters even in .raw() calls.
Stored procedures
Safe only if parameters are bound; dynamic SQL inside the procedure can reintroduce SQLi.
3. Defense in Depth
Layer these—but never skip parameterization:
Least privilege DB accounts
App user should not DROP tables or read unrelated schemas.
Allowlists for sort/order columns
Column names cannot be parameterized; pick from a fixed list in code.
WAF / RASP
Can block obvious payloads but is bypassable; treat as monitoring, not primary fix.
WAF limits
Web Application Firewalls pattern-match known SQLi strings. Encodings, novel syntax, and blind techniques slip through. Deploy a WAF for visibility and friction, but ship parameterized queries first.
Knowledge Check
The primary defense against SQL injection is:
Multiple choice
Knowledge Check
True or False: A WAF alone is sufficient to eliminate SQL injection risk.
True or False
Knowledge Check
When sorting by a user-chosen column name, you should:
Multiple choice