SQL Injection Prevention Techniques
Fast recall
Quick revision
Core answer
Whether you know layered defenses, not just parameterization.
Relying on a single technique or on manual escaping/blacklists.
Use allow-lists for identifiers and least privilege; treat escaping as last resort.
Interview-ready guide
Interview answer
A search term belongs in WHERE name LIKE ? and is bound as data. A requested sort key cannot be written as ORDER BY ?, so map newest to created_at DESC and priceLowToHigh to price ASC; reject every other value. Stored procedures are safe only when their own code binds values and avoids unsafe dynamic SQL. ORMs are also injectable when JPQL/native query strings are concatenated.
SQL Injection Prevention Techniques
Direct Answer
Bind every data value through PreparedStatement, JdbcTemplate parameters, or ORM query parameters. For SQL structure that cannot be bound—table names, column names, sort direction—map a small allow-list of public choices to fixed SQL fragments. Add least-privilege database roles, safe error handling, code review, and query tests as defense in depth. Escaping and WAF filtering are not substitutes for parameterization.
Code Example
// ? cannot parameterize a column name, so validate against an allow-list
String sortCol = request.getParameter("sort"); // e.g. "name"
List<String> allowed = List.of("name", "created_at", "email");
if (!allowed.contains(sortCol)) throw new IllegalArgumentException("bad sort");
String sql = "SELECT id, name FROM users ORDER BY " + sortCol; // safe: from allow-list
try (PreparedStatement ps = con.prepareStatement(sql)) {
ResultSet rs = ps.executeQuery();
}
// values still use ? + setXxx; only validated identifiers are concatenated
Common Mistakes & Pitfalls
- Blacklisting bad words: attackers encode/bypass — use allow-lists instead.
- Manual escaping as primary defense: fragile; parameterize instead.
- Over-privileged DB account: one injection then becomes catastrophic.
- Concatenating inside a stored procedure: dynamic SQL there is still vulnerable.
Check your understanding
Answer these without looking back at the article.
- What is SQL injection and how does it work?
- How does PreparedStatement prevent SQL injection in JDBC?
- Can SQL injection occur with JPA or Hibernate in Java?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.