Friday 13 July 2018

Calling MySQL Stored Procedures from JDBC

Calling MySQL Stored Procedures from JDBC?

In this tutorial, you will learn how to call MySQL stored procedures from JDBC using CallableStatement object.

Before you start

For the sake of demonstration, we will create a new stored procedure named get_candidate_skill that accepts candidate_id as the IN parameter and returns a result set that contains the skills of the candidate.
Let’s call this stored procedure for candidate id with value 122.
jdbc mysql stored procedure

Introducing to CallableStatement and stored procedure call syntax

To call stored procedures or stored functions in MySQL from JDBC, you use CallableStatement object, which inherits from PreparedStatement object. The general syntax of calling a stored procedure is as follows:
You wrap the stored procedure call within braces ({}). If the stored procedure returns a value, you need to add the question mark and equal (?=) before the call keyword. If a stored procedure does not return any values, you just omit the ?= sign. In case the stored procedure accepts any parameters, you list them within the opening and closing parentheses after the stored procedure’s name.
The following are examples of using the syntax for calling stored procedures in different contexts:
SyntaxStores Procedures
{  call procedure_name() }Accept no parameters and return no value
{ call procedure_name(?,?) }Accept two parameters and return no value
{?= call procedure_name() }Accept no parameter and return value
{?= call procedure_name(?) }Accept one parameter and return value
Notice that question mark placeholder (?) can be used for both IN ,OUT, and INOUT parameters. For detailed information on different parameter types in stored procedures, check it out MySQL stored procedure parameters tutorial.

JDBC MySQL stored procedure example

First, open a connection to MySQL server by creating a new Connection object.
Then, prepare a stored procedure call and create a CallableStatement object by calling prepareCall()method of the Connection object.
Next, pass all the parameters to the stored procedure. In this case, the get_candidate_skill stored procedure accepts only one IN parameter.
After that, execute the stored procedure by calling the executeQuery() method of the CallableStatement object. It returns a result set in this case.
Finally, traverse the ResultSet to display the results.
The following is the complete example of calling the MySQL stored procedure from JDBC.
Let’s run the program.

The program works as expected.
In this tutorial, we have shown you how to call a stored procedure in MySQL database from a Java program using JDBC CallableStatement object.

0 comments:

Post a Comment