Insert record into a table by using CallableStatement

Introduction 

 
In this blog we will know how to insert records in a table using CallableStatement of JDBC (Java Database Connectivity) in the console window.
Here we use Type-1 driver (JDBC-ODBC bridge)
 

Creation of dsn(database source name) for Oracle

 
Start-Control panel- Administrative Tools- Data Sources (ODBC)-go to system DSN tab-click add button-select a driver for which you want to set up a data source (for Oracle- Oracle in XE)-select it and click finish-give any name in the data source name textbox-then click ok button.
 
Note: - Here Username=system, Password=pintu and Dsn name=dsn1
 
Ex:- To insert a record into a table by using CallableStatement
 

Table Creation

  1. Create table employee(empno int, empname varchar(50), sal int)   

Stored procedure

 
Create or replace procedure addemp(no number,nm varchar,s number)
  1. as  
  2. begin  
  3. insert into employee(empno,empname,sal) values(no,nm,s);  
  4. end;  
callableDemo.java file
  1. import java.sql.*;  
  2. import java.util.*;  
  3. public class callableDemo {  
  4.  public static void main(String args[]) throws Exception {  
  5.   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  6.   Connection con = DriverManager.getConnection("jdbc:odbc:dsn1""system""pintu");  
  7.   CallableStatement cstmt = con.prepareCall("call addemp(?,?,?)");  
  8.   Scanner sc = new Scanner(System.in);  
  9.   System.out.print("Enter the Employee No: ");  
  10.   int x = sc.nextInt();  
  11.   System.out.print("Enter the Employee Name: ");  
  12.   String str = sc.next();  
  13.   System.out.println("Enter the Salary: ");  
  14.   String j = sc.next();  
  15.   cstmt.setInt(1, x);  
  16.   cstmt.setString(2, str);  
  17.   cstmt.setString(3, j);  
  18.   cstmt.execute();  
  19.   System.out.println("***Procedure called****");  
  20.   System.out.println("Record Sucessfully Inserted");  
  21.   con.close();  
  22.  }  
  23. }   
Compile
 
Javac callableDemo.java
 
Java callableDemo