JDBC – Call Stored Function in DB

Create function in database:

SQL> create or replace function calc(a in number, b in number) return number
is
c number(5);
begin
c:=a+b;
return c;
end;
/
Function created.

Code:

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.Types;
public class CallableFunction
{
            static Connection con;
            public static void main(String args[]) throws Exception
            {
                        try
                        {
                                    Class.forName(“oracle.jdbc.driver.OracleDriver”);
                                    System.out.println(“Driver is ready”);
                                    con = DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe”, “system”, “admin”);
                                    System.out.println(“Connection is ready”);
                                    CallableStatement stmt=con.prepareCall(“{?= call calc(?,?)}”); 
                                    stmt.setInt(2,10); 
                                    stmt.setInt(3,43); 
                                    stmt.registerOutParameter(1,Types.INTEGER); 
                                    stmt.execute(); 
                                    System.out.println(stmt.getInt(1));                              
                        }
                        finally
                        {
                                    if(con != null)
                                    {
                                                con.close();
                                                System.out.println(“Connection closed”);
                                    }
                        }
            }
}
Scroll to Top