SQL Injection Prevention Techniques
Protect your application from SQL injection attacks using parameterized queries, prepared statements, ORMs, and input validation. Essential security practices.
Detailed Explanation
SQL Injection Prevention Techniques
SQL injection is one of the most dangerous and common web application vulnerabilities. It occurs when untrusted input is incorporated into SQL queries without proper handling, allowing attackers to manipulate the query logic.
The Vulnerability
-- DANGEROUS: String concatenation
query = "SELECT * FROM users WHERE email = '" + userInput + "'";
-- If userInput is: ' OR '1'='1' --
-- The query becomes:
SELECT * FROM users WHERE email = '' OR '1'='1' --'
-- This returns ALL users
Parameterized Queries (The Solution)
# Python (psycopg2)
cursor.execute("SELECT * FROM users WHERE email = %s", (user_input,))
// Node.js (pg)
client.query("SELECT * FROM users WHERE email = $1", [userInput])
// Java (JDBC)
PreparedStatement stmt = conn.prepareStatement(
"SELECT * FROM users WHERE email = ?");
stmt.setString(1, userInput);
Parameters are sent separately from the query text and are never interpreted as SQL code.
ORM Protection
Most ORMs use parameterized queries by default:
# Django ORM (safe)
User.objects.filter(email=user_input)
# SQLAlchemy (safe)
session.query(User).filter(User.email == user_input)
Warning: ORMs that allow raw SQL still require parameterization for user inputs.
Defense in Depth
- Parameterized queries: Primary defense. Non-negotiable
- Input validation: Whitelist expected formats (email regex, numeric ranges)
- Least privilege: Database accounts should have only the permissions they need
- WAF rules: Web Application Firewalls can catch common injection patterns
- Escaping: Last resort only when parameterization is impossible
- Error handling: Never expose database error messages to end users
Common Injection Points
- Login forms (authentication bypass)
- Search fields and filters
- URL parameters and query strings
- HTTP headers (User-Agent, Referer)
- JSON and XML payloads in APIs
SQL injection has been the number one web vulnerability for over two decades. Parameterized queries are the definitive solution and must be used everywhere user input touches SQL.
Use Case
A development team refactors a legacy application to replace all string-concatenated SQL queries with parameterized prepared statements, eliminating SQL injection vulnerabilities across the codebase.