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.
EXAMPLE:
import java.sql.*;
class demo
{
public static void main(String[] args){
Connection con=null;
Statement stmt=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
con.setAutoCommit(false);
stmt=con.createStatement();
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();
con.commit();
}catch(BatchUpdateException e){
System.out.println("the exception is::::->"+e.getSQLState()+e.getMessage()+e.getErrorCode());
}
finally{
try{
stmt.close();
con.close();}
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