IBM DB2 Manual page 45

Table of Contents

Advertisement

|
|
|
|
|
3. Check for errors. If no errors occurred:
a. Get the number of rows that were affect by each SQL statement from the
array that the executeBatch invocation returns. This number does not
include rows that were affected by triggers or by referential integrity
enforcement.
b. If AutoCommit is disabled for the Connection object, invoke the commit
method to commit the changes.
If AutoCommit is enabled for the Connection object, the IBM Data Server
Driver for JDBC and SQLJ adds a commit method at the end of the batch.
To make batch updates using a single statement with several sets of input
parameters, follow these basic steps:
1. Invoke the prepareStatement method to create a PreparedStatement object.
2. For each set of input parameter values:
a. Execute setXXX methods to assign values to the input parameters.
b. Invoke the addBatch method to add the set of input parameters to the batch.
3. Invoke the executeBatch method to execute the statements with all sets of
parameters.
4. If no errors occurred:
a. Get the number of rows that were updated by each execution of the SQL
statement from the array that the executeBatch invocation returns.
b. If AutoCommit is disabled for the Connection object, invoke the commit
method to commit the changes.
If AutoCommit is enabled for the Connection object, the IBM Data Server
Driver for JDBC and SQLJ adds a commit method at the end of the batch.
c. If the PreparedStatement object returns automatically generated keys, call
DB2PreparedStatement.getDBGeneratedKeys to retrieve an array of ResultSet
objects that contains the automatically generated keys.
Check the length of the returned array. If the length of the returned array is
0, an error occurred during retrieval of the automatically generated keys.
5. If errors occurred, process the BatchUpdateException.
In the following code fragment, two sets of parameters are batched. An UPDATE
statement that takes two input parameters is then executed twice, once with each
set of parameters. The numbers to the right of selected statements correspond to
the previously-described steps.
try {
...
PreparedStatement prepStmt = con.prepareStatement(
"UPDATE DEPT SET MGRNO=? WHERE DEPTNO=?");
prepStmt.setString(1,mgrnum1);
prepStmt.setString(2,deptnum1);
prepStmt.addBatch();
prepStmt.setString(1,mgrnum2);
prepStmt.setString(2,deptnum2);
prepStmt.addBatch();
int [] numUpdates=prepStmt.executeBatch();
for (int i=0; i < numUpdates.length; i++) {
if (numUpdates[i] == SUCCESS_NO_INFO)
System.out.println("Execution " + i +
": unknown number of rows updated");
else
System.out.println("Execution " + i +
"successful: " numUpdates[i] + " rows updated");
}
1
2a
2b
3
4a
Chapter 3. JDBC application programming
29

Hide quick links:

Advertisement

Table of Contents
loading

Table of Contents