Prefer PreparedStatement Over Statement
ID |
java.jdbc_prefer_prepared_statement |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
best-practice, efficiency |
Description
Reports calls to Statement.executeQuery(), Statement.execute(), or Statement.executeUpdate() on a plain JDBC Statement.
Rationale
Using a plain Statement to execute SQL means the query string is sent directly to the database, bypassing precompilation. This prevents the database from caching execution plans and opens the door to SQL injection when query parameters are concatenated into the SQL string. PreparedStatement solves both problems.
// Bad - plain Statement with string concatenation
Statement stmt = conn.createStatement();
stmt.executeQuery("SELECT * FROM users WHERE id = " + userId);