CallableStatement is an interface in JDBC used to call stored procedures and functions defined in the database. It allows Java applications to execute complex SQL logic that runs directly on the database server.
java.sql packageA CallableStatement is created using the prepareCall() method of the Connection interface.
// Creating a CallableStatement to call a stored procedure
CallableStatement cs = con.prepareCall("{call procedure_name(?, ?)}");
Simulate how IN parameters travel to the DB and OUT parameters travel back.
// Calling a stored procedure with IN and OUT parameters
CallableStatement cs = con.prepareCall("{call getEmployeeName(?, ?)}");
cs.setInt(1, 101);
cs.registerOutParameter(2, java.sql.Types.VARCHAR);
cs.execute();
String name = cs.getString(2);
The stored procedure is executed in the database. The OUT parameter returns the employee name, which is retrieved using getString() in Java.
CallableStatement objects to avoid resource leaksCallableStatement