Batch Updates
Go Up to Programming with JDBC
Contents
Methods for the Statement and PreparedStatement Classes
The following methods have been added to both the Statement
and the PreparedStatement
classes. The methods listed below now work according to the JDBC specifications.
Method | Functionality |
---|---|
void Statement.addBatch(String sql) |
Adds sql to the current list of commands. |
void Statement.clearBatch() |
Empties the list of commands for the current statement object. |
int[] Statement.executeBatch() throws |
Submits the list of commands for this statement’s objects to the database for execution as a unit. The returned integer array contains the update counts for each of the SQL commands in the list. |
void PreparedStatement.addBatch() |
Adds a set of parameters to the list of commands for the current |
The BatchUpdateException Class
A new BatchUpdateException
class has been implemented in order to support JDBC Batch update functionality. Here is the list of methods and constructors in the new class:
Method/Constructor | Functionality |
---|---|
public BatchUpdateException( String reason, String SQLState, int vendorCode, int [] updateCounts) |
Constructs a
|
public BatchUpdateException( String reason, String SQLState, int [] updateCounts) |
Constructs a
The vendor code is implicitly set to zero. |
public BatchUpdateException( String reason, int [] updateCounts) |
Constructs a
The following values are implicitly set: the |
public BatchUpdateException (int [] updateCounts) |
Constructs a The following values are implicitly set: |
public BatchUpdateException() |
The following values are implicitly set:
the Open Group code identification is set to null. |
public int [] getUpdateCounts() |
Retrieves an array of |
The DatabaseMetaData.supportsBatchUpdates Function
The DatabaseMetaData.supportsBatchUpdates
function has changed as follows:
Function | Functionality |
---|---|
|
Can now return TRUE. |
Code Examples
Code example for the batch update functions:
Statement Class con.setAutoCommit(false); Statement stmt = con.createStatement(); stmt.addBatch("INSERT INTO foo VALUES (1, 10)); stmt.addBatch("INSERT INTO foo VALUES (2, 21)); int[] updateCounts = pstmt.executeBatch(); con.commit();
Code example for the PreparedStatement
class:
PreparedStatement pstmt = con.prepareStatement ("UPDATE employee set emp_id = ? where emp_id = ?") pstmt.setInt(1, newEmpId1); pstmt.setInt(2, oldEmpId1); pstmt.addBatch(); pstmt.setInt(1, newEmpId2); pstmt.setInt(2, oldEmpId2); pstmt.addBatch(); int[] updateCounts = pstmt.executeBatch();
Code example for the BatchUpdateException
class and getUpdateCounts
() method
try { int[] updateCounts = pstmt.executeBatch(); } catch (BatchUpdateException b) { int [] updates = b.getUpdateCounts(); for (int i = 0; i < updates.length; i++) { System.err.println ("Update Count " + updates[i]); } }