Input Validation and Defense in Depth
You'll learn why parameterized queries alone aren't enough—and how to build multiple layers of security when working with databases.
The Core Idea
Parameterized queries are your primary defense against SQL injection, but they're not a complete security solution. Defense in depth means building multiple independent security layers so that if one fails, others still protect you. Even with parameterization, you should validate that inputs meet expected types, ranges, and formats before they ever reach your database.
Why Validation Matters
Think of database security like airport security: metal detectors (parameterization) catch weapons, but you still check IDs, scan bags, and verify boarding passes. Each layer catches different problems.
Parameterization prevents malicious SQL code execution, but it doesn't prevent:
- Type mismatches: Passing
"hello"when you expect an integer - Range violations: Negative ages or dates in the future
- Format errors: Malformed email addresses or phone numbers
- Business logic violations: Withdrawing more money than available
Validation in Practice
Before executing a query, validate your inputs:
def validate_age(age):
if not isinstance(age, int):
raise ValueError("Age must be an integer")
if age < 0 or age > 150:
raise ValueError("Age must be between 0 and 150")
return age
# Validate FIRST
clean_age = validate_age(user_input)
# Then use parameterized query
cursor.execute("SELECT * FROM users WHERE age = ?", (clean_age,))
This catches problems early, prevents database errors, and provides better error messages to users or logs.
Key Takeaway: Parameterization stops SQL injection, but input validation catches data quality issues, enforces business rules, and creates a defense-in-depth security posture—always validate types, ranges, and formats before querying your database.