JDBC - 批处理

批处理允许您将相关的SQL语句分组到批处理中,并通过一次调用数据库来提交它们.

当您一次向数据库发送多个SQL语句时,可以减少通信开销量,从而提高性能.

  • 不需要JDBC驱动程序来支持此功能.您应该使用 DatabaseMetaData.supportsBatchUpdates()方法来确定目标数据库是否支持批量更新处理.如果JDBC驱动程序支持此功能,则该方法返回true.

  • Statement,PreparedStatement的 addBatch()方法, CallableStatement 用于向批处理添加单个语句. executeBatch()用于开始执行组合在一起的所有语句.

  • executeBatch()返回一个整数数组,数组的每个元素代表相应更新语句的更新计数.

  • 就像你可以添加语句一样要处理的批处理,可以使用 clearBatch()方法删除它们.此方法删除使用addBatch()方法添加的所有语句.但是,您无法有选择地选择要删除的语句.

使用Statement对象进行批处理

此处是一个典型的步骤,使用批处理与Statement对象和减号;

  • 使用创建一个Statement对象createStatement()方法.

  • 使用 setAutoCommit()将自动提交设置为false.

  • 在创建的语句对象上使用 addBatch()方法将您喜欢的SQL语句添加到批处理中.

  • 在创建的语句对象上使用 executeBatch()方法执行所有SQL语句.

  • 最后,使用 commit()方法提交所有更改.

示例

以下代码片段提供了使用Statement对象 : 的批量更新示例;

// Create statement object
Statement stmt = conn.createStatement();

// Set auto-commit to false
conn.setAutoCommit(false);

// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
             "VALUES(200,'Zia', 'Ali', 30)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);

// Create one more SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
             "VALUES(201,'Raj', 'Kumar', 35)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);

// Create one more SQL statement
String SQL = "UPDATE Employees SET age = 35 " +
             "WHERE id = 100";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);

// Create an int[] to hold returned values
int[] count = stmt.executeBatch();

//Explicitly commit statements to apply changes
conn.commit();


使用PrepareStatement对象进行批处理

以下是使用PrepareStatement对象和减号进行批处理的典型步骤序列;

  1. 使用占位符创建SQL语句.

  2. 使用 prepareStatement()方法创建PrepareStatement对象.

  3. 使用 setAutoCommit()将自动提交设置为false .

  4. 在创建的语句对象上使用 addBatch()方法将您喜欢的SQL语句添加到批处理中.

  5. 在创建的语句对象上使用 executeBatch()方法执行所有SQL语句.

  6. 最后,使用 commit()方法提交所有更改.

以下代码段提供了批量更新的示例使用PrepareStatement对象 :

// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
             "VALUES(?, ?, ?, ?)";

// Create PrepareStatement object
PreparedStatemen pstmt = conn.prepareStatement(SQL);

//Set auto-commit to false
conn.setAutoCommit(false);

// Set the variables
pstmt.setInt( 1, 400 );
pstmt.setString( 2, "Pappu" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 33 );
// Add it to the batch
pstmt.addBatch();

// Set the variables
pstmt.setInt( 1, 401 );
pstmt.setString( 2, "Pawan" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 31 );
// Add it to the batch
pstmt.addBatch();

//add more batches
.
.
.
.
//Create an int[] to hold returned values
int[] count = stmt.executeBatch();

//Explicitly commit statements to apply changes
conn.commit();