SQL ยท Chapter 41 of 42

SQL Injection Safety

SQL INJECTION is when user input is concatenated into a query, letting attackers change its meaning.

Prevention: ALWAYS use PARAMETERIZED queries (prepared statements). Never concatenate user input into SQL.

Example 1 (python)
# BAD โ€” string concat
name = request.form['name']
cur.execute("SELECT * FROM users WHERE name = '" + name + "'")

# GOOD โ€” parameterized
cur.execute("SELECT * FROM users WHERE name = %s", (name,))
Output
safe query

Parameter values are escaped by the driver.

Example 2 (sql)
-- Classic injection input
name = "' OR '1'='1";
-- becomes: SELECT * FROM users WHERE name = '' OR '1'='1'
-- returns EVERY user
Output
attacker sees all users

Concatenation is the entire vulnerability.

Key points

  • Never concatenate user input into SQL.
  • Use parameterized queries / prepared statements.
  • ORMs (SQLAlchemy, Django ORM, Prisma) do this by default.
  • Also validate/sanitise input as defense in depth.
๐Ÿ’ก Note: SQL injection has been the #1 web vulnerability for over a decade. The fix โ€” parameterized queries โ€” is trivial. Always use them.

๐Ÿ“ Quick Quiz

1. SQL injection is caused by:

2. The primary defense is:

3. The injection `' OR '1'='1` works because: