The CallableStatement interface is used in JDBC to call stored procedures and functions from a Java application. It helps in executing database logic that is already defined in the database.
In this chapter, you will learn about the CallableStatement interface, its usage, and how to call stored procedures and functions.
The CallableStatement interface is used to call stored procedures and functions in a database. These procedures contain precompiled business logic, which improves performance and reduces code complexity.
For example, you can create a function in the database to calculate the age of an employee based on the date of birth, and then call it from a Java program using CallableStatement.
The differences between stored procedures and functions are given below:
| Stored Procedure | Function |
|---|---|
| is used to perform business logic. | is used to perform calculations. |
| must not have the return type. | must have the return type. |
| may return 0 or more values. | may return only one values. |
| We can call functions from the procedure. | Procedure cannot be called from function. |
| Procedure supports input and output parameters. | Function supports only input parameter. |
| Exception handling using try/catch block can be used in stored procedures. | Exception handling using try/catch can't be used in user defined functions. |
The prepareCall() method of the Connection interface is used to create an instance of CallableStatement.
Syntax:
This syntax is used to call a stored procedure with parameters.
Example:
The example to get the instance of CallableStatement is given below:
In this example, the procedure myprocedure is called with two parameters.
To call the stored procedure, you need to create it in the database. Here, we are assuming that stored procedure looks like this.
The table structure is given below:
In this example, we are going to call the stored procedure INSERTR that receives id and name as the parameter and inserts it into the table user420. Note that you need to create the user420 table as well to run this application.
Now check the table in the database, value is inserted in the user420 table.
In this example, we are calling the sum4 function that receives two input and returns the sum of the given number. Here, we have used the registerOutParameter method of CallableStatement interface, that registers the output parameter with its corresponding type. It provides information to the CallableStatement about the type of result being displayed.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE, BLOB, CLOB etc.
Let's create the simple function in the database first.
Now, let's write the simple program to call the function.
Output:
53
We request you to subscribe our newsletter for upcoming updates.