Junior — Middle
What are the differences between the Statement and PreparedStatement classes in JDBC in terms of usage and performance?
sobes.tech AI
Answer from AI
Statement:
- Used for executing simple SQL queries without parameters.
- Queries are compiled each time they are executed.
- Less secure, as it is vulnerable to SQL injection when dynamically constructing queries.
PreparedStatement:
- Allows the use of parameterized queries with placeholders (e.g.,
?). - The query is compiled once and can be executed multiple times with different parameters.
- Improves performance when the same query is called repeatedly.
- More secure, as parameters are automatically escaped, reducing the risk of SQL injection.
Example:
String sql = "SELECT * FROM users WHERE id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, userId);
ResultSet rs = ps.executeQuery();
Use PreparedStatement if queries are repeated with different parameters or security is a concern.