Monday, January 19, 2009

8.1.3 Making Batch Updates

The ability to make batch updates is the same for CallableStatement objects as it is for PreparedStatement objects. In fact, a CallableStatement object is restricted to the same functionality that a PreparedStatement object has. More precisely, when using the batch update facility, a CallableStatement object can call only stored procedures that take input parameters or no parameters at all. Further, the stored procedure must return an update count. The CallableStatement.executeBatch method (inherited from PreparedStatement) will throw a BatchUpdateException if the stored procedure returns anything other than an update count or takes OUT or INOUT parameters.

The following code fragment illustrates using the batch update facility to associate two sets of parameters with a CallableStatement object.

CallableStatement cstmt = con.prepareCall(
"{call updatePrices(?, ?)}");
cstmt.setString(1, "Colombian");
cstmt.setFloat(2, 8.49f);
cstmt.addBatch();
cstmt.setString(1, "Colombian_Decaf");
cstmt.setFloat(2, 9.49f);
cstmt.addBatch();
int [] updateCounts = cstmt.executeBatch();

The variable cstmt contains a call to the stored procedure updatePrices with two sets of parameters associated with it. When cstmt is executed, two update statements will be executed together as a batch: one with the parameters Colombian and 8.49f, and a second one with the parameters Colombian_Decaf and 9.49f. An f after a number, as in 8.49f, tells the Java compiler that the value is a float; otherwise, the compiler assumes that a number with decimal digits is a double and will not allow it to be used as a float.

0 Comments: