All for Joomla All for Webmasters

Batch Processing in JDBC

Instead of executing a single query, we can execute a batch (group) of queries. It makes the performance fast.

The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing.

Advantage of Batch Processing

Fast Performance

Methods of Statement interface

The required methods for batch processing are given below:

Method Description
void addBatch(String query) It adds query into batch.
int[] executeBatch() It executes the batch of queries.

Example of batch processing in jdbc

Let’s see the simple example of batch processing in jdbc. It follows following steps:

  • Load the driver class
  • Create Connection
  • Create Statement
  • Add query in the batch
  • Execute Batch
  • Close Connection
  1. import java.sql.*;
  2. class FetchRecords{
  3. public static void main(String args[])throws Exception{
  4. Class.forName(“oracle.jdbc.driver.OracleDriver”);
  5. Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,“system”,“oracle”);
  6. con.setAutoCommit(false);
  7. Statement stmt=con.createStatement();
  8. stmt.addBatch(“insert into user420 values(190,’abhi’,40000)”);
  9. stmt.addBatch(“insert into user420 values(191,’umesh’,50000)”);
  10. stmt.executeBatch();//executing the batch
  11. con.commit();
  12. con.close();
  13. }}

If you see the table user420, two records has been added.

Example of batch processing using PreparedStatement

  1. import java.sql.*;
  2. import*;
  3. class BP{
  4. public static void main(String args[]){
  5. try{
  6. Class.forName(“oracle.jdbc.driver.OracleDriver”);
  7. Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,“system”,“oracle”);
  8. PreparedStatement ps=con.prepareStatement(“insert into user420 values(?,?,?)”);
  9. BufferedReader br=new BufferedReader(new InputStreamReader(;
  10. while(true){
  11. System.out.println(“enter id”);
  12. String s1=br.readLine();
  13. int id=Integer.parseInt(s1);
  14. System.out.println(“enter name”);
  15. String name=br.readLine();
  16. System.out.println(“enter salary”);
  17. String s3=br.readLine();
  18. int salary=Integer.parseInt(s3);
  19. ps.setInt(1,id);
  20. ps.setString(2,name);
  21. ps.setInt(3,salary);
  22. ps.addBatch();
  23. System.out.println(“Want to add more records y/n”);
  24. String ans=br.readLine();
  25. if(ans.equals(“n”)){
  26. break;
  27. }
  28. }
  29. ps.executeBatch();
  30. System.out.println(“record successfully saved”);
  31. con.close();
  32. }catch(Exception e){System.out.println(e);}
  33. }}

It will add the queries into the batch until user press n. Finally it executes the batch. Thus all the added queries will be fired.


submit to reddit

Leave a Reply