SQL Injection Defense
How does SQL injection work, and what are the primary defenses in application code?
Answers use simple, clear English.
Quick interview answer
Attackers inject SQL via unsanitized input concatenated into queries. Primary defense: parameterized queries / prepared statements (or ORM parameterized APIs). Also least-privilege DB accounts, input validation, and avoiding dynamic SQL where possible.
Detailed answer
Attackers inject SQL via unsanitized input concatenated into queries. Primary defense: parameterized queries / prepared statements (or ORM parameterized APIs). Also least-privilege DB accounts, input validation, and avoiding dynamic SQL where possible. Escaping strings manually is fragile. ORMs can still be unsafe with raw SQL APIs if you concatenate.
Full explanation
ORMs can still be unsafe with raw SQL APIs if you concatenate.
Real example & use case
Login form ' OR 1=1-- bypassing auth when query is string-built.
Pros & cons
Pros of parameters: engine separates code/data. Cons: dynamic IN-lists and identifiers still need careful handling (allowlists).
Code example
-- Vulnerable:
-- "SELECT * FROM users WHERE name = '" + name + "'"
-- Safe (parameter):
SELECT * FROM users WHERE name = @name;Practice code · sql (view only · no execution)
-- Vulnerable:
-- "SELECT * FROM users WHERE name = '" + name + "'"
-- Safe (parameter):
SELECT * FROM users WHERE name = @name;