Batch Processing in JDBC

Batch Processing

Batch processing helps us to execute multiple SQL statements in batch instead of executing a single query.

Java batch makes it easier to process large amounts of data and manage how data is processed. It is used for payment processing, payroll, claim processing, inventory management etc.

Methods used in Batch Processing

The Batch Processing uses some methods which are defined in Statement interface.

1. void addBatch(String sql)
The addBatch( ) method is defined in Statement interface. It is used to add individual query in a batch (group).

2. int[ ] executeBatch()
This method is used to start the execution batch of statement. It returns an integer array.

3. voidclearBatch( )
It is defined in Statement interface. It removes all the statement objects which are added with the addBatch( ) method.

Example : Implementing Batch Processing in JDBC

// BatchDemo.java

import java.sql.*;
import java.io.*;
classBatchDemo
{
     public static void main(String args[])
     {
         Connection conn = null;
         Statement stmt = null;
         try
         {
              Class.forName("oracle.jdbc.driver.OracleDriver");
              conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "scott", "tiger");
              conn.setAutoCommit(false);
              stmt = conn.createStatement( );
              stmt.addBatch("insert into Student values (101, 'ABC', 'MCA')");
              stmt.addBatch("insert into Student values (102, 'XYZ', 'MCA')");
              stmt.addBatch("insert into Student values(105, 'PQR', 'BE')");
              stmt.executeBatch();
              conn.commit();
         }
         catch(Exception e)
         {
              e.printStackTrace();
         }
         finally
         {
              try
              {
                  if(conn != null)
                  {
                       conn.close();
                  }
              }
              catch(SQLException e)
              {
                   e.printStackTrace();
              }
                   try
                   {
                        if(stmt != null)
                        {
                             stmt.close();
                        }
                   }
                   catch(SQLException e)
                   {
                        e.printStackTrace();
                   }
         }
     }
}