How to call the function using JDBC

The CallableStatement interface is also used to call the function.

In this example, we are calling the add 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.

1. create or replace function add
2. (
3. x in number,
4. y in number
5. )
6. return number
7. is
8. temp number(8);
9. begin
10. temp :=x+y;
11. return temp;
12. end;
13. /

Now, let's write the simple program to call the function.

import java.sql.*;
public class Addition
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
CallableStatement stmt=con.prepareCall("{?= call add(?,?)}");
stmt.setInt(2,15);
stmt.setInt(3,20);
stmt.registerOutParameter(1,Types.INTEGER);
stmt.execute();
System.out.println(stmt.getInt(1));
}
}

Output
35

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment