SQL Injection Prevention Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓SQL Injection Prevention runs in O(n) time and O(n) space, in Java as in every other language.
- ✓java.sql is in the JDK, so the boundary is PreparedStatement: connection.prepareStatement("select ...
- ✓A PreparedStatement even when the SQL has no parameters at all, inside try-with-resources, with setNull(i, Types.VARCHAR) rather than setObject(i, null) so the driver knows the type it is sending.
- ✓The Java trap: JDBC being safe does not make the application safe, because JPA introduces a second parser.
- ✓Server-side preparation is a driver setting, not a language guarantee. The PostgreSQL JDBC driver runs a PreparedStatement client-parsed for the first few executions and only switches to a named server-side statement after prepareThreshold executions of that same object, five by default, so a statement freshly created per request never gets there: hold it or pool it.
What SQL Injection Prevention actually is
SQL Injection Prevention in Java: what you actually reach for
Java implementation
import java.sql.*;
import java.util.*;
public final class CustomerSearch {
// ORDER BY cannot be bound: the plan is built before the bind phase.
private enum Sort {
CREATED("created_at"), NAME("display_name");
final String column;
Sort(String column) { this.column = column; }
}
public List<String> search(Connection conn, String term, String sort, int limit)
throws SQLException {
// valueOf throws on anything not in the enum: that is the allowlist.
Sort s = Sort.valueOf(sort.toUpperCase(Locale.ROOT));
String sql = "SELECT display_name FROM customer WHERE display_name LIKE ? "
+ "ORDER BY " + s.column + " DESC LIMIT ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, "%" + term + "%");
ps.setInt(2, limit);
try (ResultSet rs = ps.executeQuery()) {
List<String> out = new ArrayList<>();
while (rs.next()) {
out.add(rs.getString(1));
}
return out;
}
}
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for SQL Injection Prevention?
java.sql is in the JDK, so the boundary is PreparedStatement: connection.prepareStatement("select ... where id = ?"), then setString, setInt or setObject by 1-based index. Statement is the type that should not appear in new code. Java 9 brought the identifier case into the same package with Statement.enquoteIdentifier(String, boolean) and enquoteLiteral(String), sitting on DatabaseMetaData.getIdentifierQuoteString(). Spring's NamedParameterJdbcTemplate maps :name onto those setters through MapSqlParameterSource, and JPA binds with TypedQuery.setParameter using :name or ?1.
What is the most common Java mistake when implementing SQL Injection Prevention?
JDBC being safe does not make the application safe, because JPA introduces a second parser. em.createQuery("from Customer where name = '" + name + "'") is HQL injection: Hibernate parses that string itself and translates it into the SQL it then binds, so untrusted text became syntax long before JDBC saw anything. The same applies to @Query(nativeQuery = true) assembled by concatenation. The other Java-shaped surprise is inherited API: PreparedStatement extends Statement, so ps.execute(String) compiles cleanly and the specification requires it to throw at runtime. The compiler will not stop you calling the unparameterised overload on a prepared object.
How does SQL Injection Prevention actually perform in Java?
Server-side preparation is a driver setting, not a language guarantee. The PostgreSQL JDBC driver runs a PreparedStatement client-parsed for the first few executions and only switches to a named server-side statement after prepareThreshold executions of that same object, five by default, so a statement freshly created per request never gets there: hold it or pool it. MySQL Connector/J defaults useServerPrepStmts=false and emulates binding client-side. Autoboxing on setObject with an Integer costs an allocation per call, which only matters in tight loops where addBatch and executeBatch are the real win. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.