Junior
What is the difference between Statement and PreparedStatement in Java?
sobes.tech AI
Answer from AI
Statement is used for executing static SQL queries. It is suitable when the query does not contain input parameters.
PreparedStatement is a subclass of Statement. It is used for executing parameterized SQL queries. Queries are precompiled, which improves performance and security by preventing SQL injection.
Key differences:
- Security: PreparedStatement protects against SQL injection by automatically escaping special characters in input parameters. Statement requires manual handling of input data.
- Performance: PreparedStatement is compiled once and can be reused with different parameters, saving time when executing queries, especially in loops. Statement is recompiled each time it is executed.
- Convenience: PreparedStatement allows the use of placeholders (?) for parameters, making the code more readable and easier to work with variable data.
Example of using Statement:
// Assuming an active connection 'connection'
String query = "SELECT * FROM users WHERE username = '" + username + "'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
Example of using PreparedStatement:
// Assuming an active connection 'connection'
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, username); // Setting the parameter
ResultSet resultSet = preparedStatement.executeQuery();