In JDBC, a CallableStatement is used to execute SQL stored procedures and functions. It allows you to call database functions or stored procedures from Java, passing parameters and retrieving results.
For PostgreSQL, you can use CallableStatement to execute stored procedures or functions that have been defined in the database.
Steps for Using CallableStatement:
- Create a stored procedure or function in PostgreSQL.
- Call the stored procedure or function from Java using
CallableStatement. - Handle input and output parameters.
Example 1: Creating a Stored Procedure in PostgreSQL
Before using CallableStatement in JDBC, let's first create a stored procedure or function in the PostgreSQL database.
Creating a Stored Function in PostgreSQL:
This function takes two integers as input and returns their sum.
Example 2: Calling a PostgreSQL Function with CallableStatement in JDBC
Now, we will write a Java program that calls this function using CallableStatement.
Java Code to Call a Stored Function
Explanation of the Java Code:
Create a
CallableStatement:?is a placeholder for the output parameter.call add_numbers(?, ?)is the call to the stored functionadd_numbers, where the first?represents the return value, and the other two?represent the input parameters.
Register the Output Parameter:
- Registers the first parameter (the return value of the function) as an output parameter of type
INTEGER.
- Registers the first parameter (the return value of the function) as an output parameter of type
Set the Input Parameters:
- Sets the input parameters for the stored function (
5and10).
- Sets the input parameters for the stored function (
Execute the Callable Statement:
- Executes the stored function.
Retrieve the Output Parameter:
- Retrieves the result of the function from the first parameter (the return value).
Close Resources:
- The
try-with-resourcesstatement ensures that theConnectionandCallableStatementare automatically closed.
- The
Comments
Post a Comment