Concept Explanation
This is the single most important security topic in database programming. Gluing user input into a SQL string lets an attacker rewrite your query.
Consider a login built by concatenation:
// NEVER DO THIS
String sql = "SELECT * FROM users WHERE name = '" + input + "'";
If the user types ' OR '1'='1, the query becomes:
SELECT * FROM users WHERE name = '' OR '1'='1'
'1'='1' is always true, so every row matches and the attacker logs in as anyone. Worse input ('; DROP TABLE users; --) can destroy data.
The Fix: Parameterised Queries
A PreparedStatement sends the query structure and the values to the database separately. Values can never be reinterpreted as SQL syntax.
String sql = "SELECT id, email FROM users WHERE name = ? AND active = ?";
try (PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, userInput); // placeholders are 1-indexed
pst.setBoolean(2, true);
try (ResultSet rs = pst.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " -> " + rs.getString("email"));
}
}
}
Now ' OR '1'='1 is treated as a literal name to search for. It simply finds nothing.
Setter Methods
| Method | Java type |
|---|---|
setString | String |
setInt, setLong | whole numbers |
setDouble, setBigDecimal | decimals (use BigDecimal for money) |
setBoolean | boolean |
setTimestamp | dates and times |
setNull | explicit SQL NULL |
The Performance Bonus
Databases cache the execution plan for a prepared query. Running the same statement in a loop with different values is measurably faster than sending a fresh string each time.
Common Mistakes
- Zero-indexed placeholders:
setString(0, ...)throws. Parameters start at 1. - Quoting the placeholder: Write
name = ?, nevername = '?'— the latter is a literal question mark. - Parameterising identifiers: Table and column names cannot be placeholders. Validate those against an allow-list instead.
- Thinking an ORM makes you safe: Hibernate raw queries are just as injectable if you concatenate.
Best Practices
- Treat concatenated SQL as a bug: If user data touches a query string, rewrite it.
- Least privilege: The app's database user should not have DROP rights.
- Never echo raw SQL errors to users — they reveal your schema.
Practice Exercises
- The Attack: Build a deliberately vulnerable concatenated query in a throwaway database and log in with
' OR '1'='1. Then fix it with a PreparedStatement and confirm the attack fails. - The Batch Insert: Use one PreparedStatement in a loop with
addBatch()andexecuteBatch()to insert 100 rows. - The Allow-List: Write a method that accepts a column name to sort by, validating it against a fixed set before building the query.