Sobes.tech
Junior — Middle

How can you invoke stored procedures in Java using the JDBC API?

sobes.tech AI

Answer from AI

The CallableStatement interface is used in Java via JDBC to call stored procedures. It allows executing procedures with input and output parameters.

Example of calling a procedure with two input parameters and one output parameter:

String sql = "{call my_procedure(?, ?, ?)}"; // last parameter is output
try (CallableStatement stmt = connection.prepareCall(sql)) {
    stmt.setInt(1, 10); // input parameter 1
    stmt.setString(2, "test"); // input parameter 2
    stmt.registerOutParameter(3, Types.INTEGER); // register output parameter

    stmt.execute();

    int result = stmt.getInt(3); // get output parameter value
    System.out.println("Result: " + result);
}

Main steps:

  • Create a CallableStatement via Connection.prepareCall() with the SQL call.
  • Set input parameters using setXXX() methods.
  • Register output parameters using registerOutParameter().
  • Execute the call with execute().
  • Retrieve output parameters using getXXX().

Thus, CallableStatement is the main tool for working with stored procedures in JDBC.

How can you invoke stored procedures in Java using… - sobes.tech