JDBC · Lesson 4
Statement vs PreparedStatement
Choosing a JDBC Statement
JDBC offers Statement, PreparedStatement, and CallableStatement for sending SQL to a database. A PreparedStatement separates SQL structure from values, which improves safety and often lets the database reuse a query plan. The right choice makes database code easier to review and less vulnerable to injection.
Using PreparedStatement
Create placeholders with ? and bind values with typed setter methods. The database receives the SQL structure separately from user input.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class CustomerLookup {
public String findCustomerName(Connection connection, long customerId) throws Exception {
String sql = "SELECT name FROM customers WHERE id = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, customerId);
try (ResultSet results = statement.executeQuery()) {
return results.next() ? results.getString("name") : null;
}
}
}
}
Statement Comparison
| Type | Parameters | Best use | Main concern |
|---|---|---|---|
Statement | None | Fixed administrative SQL | Injection risk with concatenation |
PreparedStatement | Typed placeholders | User input and repeated SQL | Must bind every value |
CallableStatement | IN and OUT parameters | Stored procedures | Database-specific contracts |
Common Mistake and Practices
Common Mistake: Building SQL with string concatenation from a request parameter. An input such as a crafted username can change the meaning of the SQL and expose data.
- Prefer
PreparedStatementfor application queries. - Bind values with the matching setter type.
- Keep SQL readable and parameterized.
- Close statements with try-with-resources.
- Check update counts when changing data.
Real-World Use Case
A customer search endpoint accepts a user-entered email address. A prepared statement safely binds that email and returns only the matching account without allowing the search text to become executable SQL.
Quiz Check