How to Call a Stored Procedure JDBC?
We have seen how we can create Stored Procedures in MySQL. This blog will show how we can Call a Stored Procedure in JDBC.
In this blog, we will create a simple procedure to perform addition between two numbers and get the result and will try to call this procedure using JDBC.
Following is the stored procedure we have created you can copy the code from here…
We can call this procedure from MySQL workbench as shown in the below image
Now we will write a simple Java program and call the procedure with the help of JDBC.
We need to consider three types of parameters:
- IN parameter: This is the default parameter type used to provide input values while calling a Stored procedure or function.
- OUT parameter: This is used to fetch output values from a procedure. No initial value is provided to an OUT parameter. Its value is set by the procedure and returned.
- INOUT parameter: This is similar to the OUT parameter except an initial value is provided which is modified by the procedure and returned.
Following is the program to call the procedure.
Output for the above example is as below:
Let’s check how to run the procedure with a out parameter.
Following is the Procedure created for the out parameter you can copy the code from here…
Java example to run the above procedure using JDBC:
We can register output parameters by using the registerOutParameter method of the CallableStatement interface.
Since we are setting the output parameter at the 3rd position we can read the result from the callable statement after executing by using getString(3) as shown in the below example.
Output for the above example is as below
You can copy Java code from CallingStoredProcedure and DatabaseConnector.