Junior
What is the difference between PreparedStatement and Statement?
sobes.tech AI
Answer from AI
Statement is used for executing static SQL queries. It is compiled each time it is executed.
PreparedStatement is used for executing parameterized SQL queries. The query is compiled once when the PreparedStatement object is created and can be executed multiple times with different parameter values.
Main differences:
| Feature | Statement | PreparedStatement |
|---|---|---|
| Performance | Compiled each time it is executed. | Compiled once. More efficient for repeated use. |
| Security | Vulnerable to SQL injection when concatenating strings. | Protects against SQL injection through automatic parameter escaping. |
| Parameters | Does not support parameterized queries. | Supports parameterized queries (?). |
| Readability | Less readable when working with large amounts of data. | More readable when working with parameters. |
Example of using Statement:
// Example with Statement (vulnerable to SQL injection)
String user = "admin";
String pass = "' OR '1'='1"; // SQL injection example
String query = "SELECT * FROM users WHERE username = '" + user + "' AND password = '" + pass + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
Example of using PreparedStatement:
// Example with PreparedStatement (protected from SQL injection)
String user = "admin";
String pass = "' OR '1'='1";
String query = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1, user);
pstmt.setString(2, pass);
ResultSet rs = pstmt.executeQuery();