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:
- Obtain a connection to the database (
Connection). - Create a
CallableStatementusing JDBC syntax for calling stored procedures. - Set input parameters (if any).
- Register output parameters (if any) with their data types.
- Execute the call using
execute()orexecuteUpdate(). - Retrieve output parameter values (if any).
- Process the
ResultSet(if the procedure returns a result set). - 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, ...)}.