Skip to main content

Java: CallableStatement Interface

Java CallableStatement Interface

CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database by the use of stored procedures and functions that will make the performance better because these are precompiled.

Suppose you need the get the age of the employee based on the date of birth, you may create a function that receives date as the input and returns age of the employee as the output.


What is the difference between stored procedures and functions.

The differences between stored procedures and functions are given below:

Stored ProcedureFunction
is used to perform business logic.is used to perform calculation.
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.

How to get the instance of CallableStatement?

The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is given below:

  1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");  

The example to get the instance of CallableStatement is given below:

  1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");  

It calls the procedure myprocedure that receives 2 arguments.


Full example to call the stored procedure using JDBC

To call the stored procedure, you need to create it in the database. Here, we are assuming that stored procedure looks like this.

  1. create or replace procedure "INSERTR"  
  2. (id IN NUMBER,  
  3. name IN VARCHAR2)  
  4. is  
  5. begin  
  6. insert into user420 values(id,name);  
  7. end;  
  8. /     

The table structure is given below:

  1. create table user420(id number(10), name varchar2(200));  

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.

  1. import java.sql.*;  
  2. public class Proc {  
  3. public static void main(String[] args) throws Exception{  
  4.   
  5. Class.forName("oracle.jdbc.driver.OracleDriver");  
  6. Connection con=DriverManager.getConnection(  
  7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  8.   
  9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");  
  10. stmt.setInt(1,1011);  
  11. stmt.setString(2,"Amit");  
  12. stmt.execute();  
  13.   
  14. System.out.println("success");  
  15. }  
  16. }  

Now check the table in the database, value is inserted in the user420 table.


Example to call the function using JDBC

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.

  1. create or replace function sum4  
  2. (n1 in number,n2 in number)  
  3. return number  
  4. is   
  5. temp number(8);  
  6. begin  
  7. temp :=n1+n2;  
  8. return temp;  
  9. end;  
  10. /  

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

  1. import java.sql.*;  
  2.   
  3. public class FuncSum {  
  4. public static void main(String[] args) throws Exception{  
  5.   
  6. Class.forName("oracle.jdbc.driver.OracleDriver");  
  7. Connection con=DriverManager.getConnection(  
  8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  9.   
  10. CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}");  
  11. stmt.setInt(2,10);  
  12. stmt.setInt(3,43);  
  13. stmt.registerOutParameter(1,Types.INTEGER);  
  14. stmt.execute();  
  15.   
  16. System.out.println(stmt.getInt(1));  
  17.           
  18. }  
  19. }  
Output: 53


Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&