Insert record into a table by using PreparedStatement


In this blog, we will know how to insert records in a table using PreparedStatement 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 PreparedStatement

Table Creation 

  1. create table employee(empno int,empname varchar(50),sal int)  
  1. import java.sql.*;  
  2. import java.util.*;  
  3. public class prepareDemo  
  4. {  
  5.  public static void main(String args[]) throws Exception   
  6.  {  
  7.   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  8.   Connection con = DriverManager.getConnection("jdbc:odbc:dsn1""system""pintu");  
  9.   PreparedStatement pstmt = con.prepareStatement("insert into employee(empno,empname,sal) values(?,?,?)");  
  10.   Scanner sc = new Scanner(;  
  11.   System.out.print("Enter the Employee Number : ");  
  12.   int empno = sc.nextInt();  
  13.   System.out.print("Enter the Employee Name : ");  
  14.   String empname =;  
  15.   System.out.print("Enter the Employee's salary : ");  
  16.   int sal = sc.nextInt();  
  17.   pstmt.setInt(1, empno);  
  18.   pstmt.setString(2, empname);  
  19.   pstmt.setInt(3, sal);  
  20.   pstmt.executeUpdate();  
  21.   System.out.println("record inserted");  
  22.   con.close();  
  23.  }  
  24. }  


Java prepareDemo