Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

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


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc







 PreviousNext