Insert Records

Insert a record into table

This tutorial provides an example on how to insert a record into table using JDBC application.

Note

Before going into the program, it is advised to go through JDBC Programming Basic Steps where the meaning of Connection, Statement etc. are discussed.

E.g

import java.sql.*;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class CreateTableDemo { 
   public static void main(String[] args) throws Exception {
      String sqlQuery = "insert into emp values(100,'Ashok Kumar',45000,'Bhimavaram')"; 
      Class.forName("oracle.jdbc.OracleDriver"); 
      Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger"); 
      Statement st = con.createStatement();
      int updateCount = st.executeUpdate(sqlQuery);
      System.out.println("The number of rows inserted :"+updateCount);
      con.close();
   }
}

Note

From SQL Plus Command Prompt, if we are performing any Database Operations then compulsory we should perform Commit Operation explicitly because Auto Commit Mode is not enabled. From JDBC Application if we perform any Database Operations then the Results will be committed automatically and we are not required to Commit explicitly, because in JDBC Auto Commit is enabled by default.

Insert Multiple Records into Table
import java.sql.*;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class InsertRecordDemo { 
   public static void main(String[] args) throws Exception {
      String sqlQuery = "insert into emp values(100,'Ashok Kumar',45000,'Bhimavaram')"; 
      Class.forName("oracle.jdbc.OracleDriver"); 
      Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger"); 
      Statement st = con.createStatement();
      Scanner sc = new Scanner(System.in);
      while(true) {
         System.out.println("Employee Number:");
         int eno=sc.nextInt();
         System.out.println("Employee Name:"); 
         String ename=sc.next(); 
         System.out.println("Employee Sal:"); 
         double esal=sc.nextDouble();
         System.out.println("Employee Address:");
         String eaddr=sc.next(); 
         String sqlQuery=String.format("insert into employees values(%d,'%s',%f,'%s')",eno,ename,esal,eaddr);
         st.executeUpdate(sqlQuery);
         System.out.println("Record Inserted Successfully"); 
         System.out.println("Do U want to Insert one more record[Yes/No]:"); 
         String option = sc.next(); 
         if(option.equalsIgnoreCase("No")) {
            break;
         }
      }
      con.close();
   }
}
Insert Records


Scroll to top