Sobes.tech
Junior

How can you invoke a stored procedure?

sobes.tech AI

Answer from AI

You can use java.sql.CallableStatement to invoke a stored procedure.

Main steps:

  1. Obtain a connection to the database (Connection).
  2. Create a CallableStatement using JDBC syntax for calling stored procedures.
  3. Set input parameters (if any).
  4. Register output parameters (if any) with their data types.
  5. Execute the call using execute() or executeUpdate().
  6. Retrieve output parameter values (if any).
  7. Process the ResultSet (if the procedure returns a result set).
  8. Close resources (CallableStatement, Connection).

Example of calling a procedure without parameters:

// Assuming connection is already established
try (CallableStatement stmt = connection.prepareCall("{call my_procedure()}")) {
    stmt.execute();
} catch (SQLException e) {
    e.printStackTrace();
}

Example of calling a procedure with input and output parameters:

// Assuming connection is already established
int inputId = 10;
String outputName = null;

try (CallableStatement stmt = connection.prepareCall("{call get_user_name(?, ?)}")) {
    stmt.setInt(1, inputId); // Set input parameter
    stmt.registerOutParameter(2, java.sql.Types.VARCHAR); // Register output parameter

    stmt.execute(); // Execute the call

    outputName = stmt.getString(2); // Get output parameter value
    System.out.println("User name: " + outputName);

} catch (SQLException e) {
    e.printStackTrace();
}

Example of calling a procedure that returns a ResultSet:

// Assuming connection is already established
try (CallableStatement stmt = connection.prepareCall("{call get_all_users()}");
     ResultSet rs = stmt.executeQuery()) { // Use executeQuery for procedures returning ResultSet

    while (rs.next()) {
        // Process each row, for example:
        int id = rs.getInt("id");
        String name = rs.getString("name");
        System.out.println("ID: " + id + ", Name: " + name);
    }

} catch (SQLException e) {
    e.printStackTrace();
}

It is important to use the correct syntax for calling based on your specific DBMS and JDBC driver. The general format is: {call procedure_name(param1, param2, ...)}.

How can you invoke a stored procedure? — Java - sobes.tech