C

Web › Module 1 › Lesson 4

BeginnerModule 1Lesson 4/6

Prevention Techniques

Prepared statements, ORMs, input validation, and why WAFs are a seatbelt—not the engine

15 min+47 XP3 quiz
Module progress4 of 6

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 out

Use 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

1

The primary defense against SQL injection is:

Multiple choice

Knowledge Check

2

True or False: A WAF alone is sufficient to eliminate SQL injection risk.

True or False

Knowledge Check

3

When sorting by a user-chosen column name, you should:

Multiple choice

← Previous

Answer all 3 knowledge checks to continue. (0/3 answered)