Search code examples
javajdbc

Can CallableStatement be used in place of PreparedStatement?


Need some help with a JDBC query. I would have tried it out myself, but right now I do not have access to a database.

My question is: Since CallableStatement extends PreparedStatement, does this mean we can use CallableStatement to execute any query prepared for prepared statement?

More specifically, any downsides to using Callable like this:

CallableStatement stmt = null;
String sql = "UPDATE Employees set age=30 WHERE id=";
      stmt = conn.prepareCall(sql);
      int empID = 102;
      stmt.setInt(1, empID); );
      stmt.execute();
stmt.close();
conn.close();

Solution

  • Yes, you can. Difference of prepareCall and prepareStatement methods described in documentation. As you can see they a just optimized for different tasks.

    package com.company;
    
    import java.sql.*;
    
    public class Main {
    
        public static void main(String[] args) throws ClassNotFoundException, SQLException {
            Class.forName("com.mysql.jdbc.Driver");
    
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/mysql", "user", "password");
    
            CallableStatement callableStatement = connection.prepareCall("SELECT * FROM db WHERE user = ?");
            callableStatement.setString(1, "deployer");
            ResultSet resultSet = callableStatement.executeQuery();
    
            while(resultSet.next()) {
                System.out.println(resultSet.getString("Db"));
            }
    
            connection.close();
        }
    }