在 JDBC 应用程序中进行批量查询

IBM® Data Server Driver for JDBC and SQLJ 提供了 IBM Data Server Driver for JDBC and SQLJ-only DB2PreparedStatement 接口,允许您对同类批处理执行批处理查询。

过程

要使用具有多组输入参数的单个语句进行批量查询,请执行下列基本步骤:

  1. 调用 prepareStatement 方法以使用输入参数为 SQL 语句创建 PreparedStatement 对象。
  2. 对于每组输入参数值:
    1. 执行 PreparedStatement.setXXX 方法以将值分配给输入参数。
    2. 调用 PreparedStatement.addBatch 方法以将输入参数集添加到批处理。
  3. PreparedStatement 对象强制转换为 DB2PreparedStatement 对象,并调用 DB2PreparedStatement.executeDB2QueryBatch 方法以执行具有所有参数集的语句。
  4. 在循环中,检索 ResultSet 对象:
    1. 检索每个 ResultSet 对象。
    2. 从每个 ResultSet 对象检索所有行。

示例

在以下代码片段中,对两组参数进行了批处理。 然后,两次执行采用一个输入参数的 SELECT 语句,每个参数值使用一次。 所选语句右边的数字对应于先前描述的步骤。
java.sql.Connection con = java.sql.DriverManager.getConnection(url, properties);
java.sql.Statement s = con.createStatement();
// Clean up from previous executions
try {
  s.executeUpdate ("drop table TestQBatch");
}
catch (Exception e) {
}

// Create and populate a test table
s.executeUpdate ("create table TestQBatch (col1 int, col2 char(10))");
s.executeUpdate ("insert into TestQBatch values (1, 'test1')");
s.executeUpdate ("insert into TestQBatch values (2, 'test2')");
s.executeUpdate ("insert into TestQBatch values (3, 'test3')");
s.executeUpdate ("insert into TestQBatch values (4, 'test4')");
s.executeUpdate ("insert into TestQBatch values (1, 'test5')");
s.executeUpdate ("insert into TestQBatch values (2, 'test6')");

try {
  PreparedStatement pstmt =                              1 
    con.prepareStatement("Select * from TestQBatch where col1 = ?");
  pstmt.setInt(1,1);                                     2a 
  pstmt.addBatch();                                      2b 
  // Add some more values to the batch
  pstmt.setInt(1,2);
  pstmt.addBatch();
  pstmt.setInt(1,3);
  pstmt.addBatch();
  pstmt.setInt(1,4);
  pstmt.addBatch();
  ((com.ibm.db2.jcc.DB2PreparedStatement)pstmt).executeDB2QueryBatch();
                                                         3 
} catch(BatchUpdateException b) {
  // process BatchUpdateException
}
ResultSet rs;
while(pstmt.getMoreResults()) {                          4 
  rs = pstmt.getResultSet();                             4a 
  while (rs.next()) {                                    4b 
    System.out.print (rs.getInt (1) + "  ");
    System.out.println (rs.getString (2));
  }
  System.out.println();
  rs.close ();
}
// Clean up
s.close ();
pstmt.close ();
con.close ();