Junior — Middle
What is the difference between using PreparedStatement and CallableStatement when working with a database?
sobes.tech AI
Answer from AI
The main difference between PreparedStatement and CallableStatement in Java when working with a database:
-
PreparedStatement is used for executing precompiled SQL queries (usually SELECT, INSERT, UPDATE, DELETE). It allows safe parameter substitution, preventing SQL injection.
-
CallableStatement is designed for calling stored procedures or functions defined in the database. It supports both input and output parameters.
Example of using PreparedStatement:
String sql = "SELECT * FROM users WHERE id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, 10);
ResultSet rs = ps.executeQuery();
Example of using CallableStatement:
CallableStatement cs = connection.prepareCall("{call getUserById(?)}");
cs.setInt(1, 10);
ResultSet rs = cs.executeQuery();
Thus, PreparedStatement is for regular parameterized queries, while CallableStatement is for calling database procedures.