What is Batch update?

In batch update set of many update statements submitted to the database for processing as a unit. It is more efficient than sending individually. All the SQL statements belong to transaction should be kept in a batch. The executeBatch() method is called to execute the entire batch.
A way of doing batch update is by sending multiple executeUpdate statements in a same transaction. Therefore they are committed and roll back as a unit. We can not add the statement that returns ResultSet to the list.
SQL commands are added to the batch or list by addBatch() method.After adding all the statements call executeBatch() method to execute the whole batch.
Batch update Exception:
-When one of the SQL statement added to the batch generates ResultSet.
-When one of the SQL statements in the batch does not execute successfully.

import java.sql.*;
class demo
public static void main(String[] args){
Connection con=null;
Statement stmt=null;
stmt.addBatch("insert into emp values(11,'mahesh','calcutta')");
stmt.addBatch("insert into emp values(12,'arjan','bhadrak')");
stmt.addBatch("insert into emp values(13,'arvind','panjab')");
int[] updatecount=stmt.executeBatch();
}catch(BatchUpdateException e){
System.out.println("the exception is::::->"+e.getSQLState()+e.getMessage()+e.getErrorCode());
catch(Exception e){
System.out.println("2nd try block exception:::->"+e);
Here Statement object send the three SQL commands to the database as a batch in this statement below
Updatecount stores the int values indicating number of rows affected by each command, all of which are one because an insertion affects one row.

No comments:

Post a Comment