Database API Safety and Parameterization
What you'll learn: How to distinguish between dangerous query construction that enables SQL injection and safe parameterized queries that protect your database.
The Core Problem
When you build database queries by concatenating or inserting user input directly into SQL strings, you create a vulnerability. Attackers can inject malicious SQL code that your database executes as commands, not data. Think of it like asking someone to "go to the store and buy [user input]" — if they say "nothing, then rob the register," you've given them control over the entire instruction.
Unsafe Query Construction
Dangerous patterns include:
- String concatenation:
"SELECT * FROM users WHERE id = " + userId - String formatting:
f"DELETE FROM posts WHERE author = '{username}'" - Raw SQL builders: Any API that directly splices user input into query text
These treat user input as executable code, not data values.
Safe Parameterized Queries
Parameterized queries (also called prepared statements) separate SQL structure from data. The database receives two things separately:
- The query template with placeholders
- The actual data values
Example concept (syntax varies by library):
- Template:
"SELECT * FROM users WHERE id = ?" - Parameter:
[userId]
The database treats the parameter as pure data, never as executable SQL. Even if a user sends "1 OR 1=1", it searches for that exact string, not a logic condition.
Across Different Tools
- Raw database APIs: Use placeholder syntax (?, $1, :name)
- ORMs (Object-Relational Mappers): Built-in query methods usually parameterize automatically, but beware "raw query" or "execute" functions that accept strings
- Query builders: Safe when using their parameter methods, unsafe when concatenating
Key Takeaway: Always use parameterized queries or ORM-provided safe methods to prevent SQL injection; never construct queries by concatenating user input into SQL strings, regardless of which database library you use.