
The Statement object can also be associated with more than one command at a time. These chunks of commands are known as batch of statements. Commands are added to the list with the Statement method addBatch and the method executeBatch submits stmt's list of commands to the underlying DBMS for execution. The execution of a batch may throw BatchUpdateException if something goes worng with the execution. All the statements only return the simple count and not any resultsets. In other words we can say the select statements are not allowed in batch statements. A Statement object's list of commands can be emptied by calling the method clearBatch on it. The following example will execute the batch of select statements.
package com.visualbuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BatchProcessingExample {
/**
* @param args
*/
public static void main(String[] args) {
try {
/** Loading the ODBC- Bridge driver*/
Class.forName("com.mysql.jdbc.Driver");
/** Getting Connection*/
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
/**Creating Statement*/
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO visualbuilder VALUES(11,'visual')");
stmt.addBatch("INSERT INTO visualbuilder VALUES(12,'Builder')");
stmt.addBatch("INSERT INTO visualbuilder VALUES(13,'RAD')");
stmt.addBatch("INSERT INTO visualbuilder VALUES(14,'Eclipse')");
stmt.addBatch("INSERT INTO visualbuilder VALUES(15,'NetBeans')");
int [] updateCounts= stmt.executeBatch();
con.commit();
con.setAutoCommit(true);
System.out.println("Batch Successful");
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:-
Batch Successful
Note :- JDBC drivers are not required to support batch updates, so a particular driver might not implement the methods addBatch, clearBatch, and executeBatch. Normally a programmer knows whether a driver that he/she is working with supports batch updates, but if an application wants to check, it can call the DatabaseMetaData method supportsBatchUpdates to find out.
Java Discussion
- - Interviewing Next week -
- - Sudoku solver
- - Setting tab order in swin
- - Java opportunities
- - Struts


