目录

JDBC - 批处理( Batch Processing)

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

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

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

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

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

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

使用Statement对象进行批处理

以下是使用语句对象批处理的典型步骤序列 -

  • 使用createStatement()方法创建Statement对象。

  • 使用setAutoCommit()将auto-commit设置为false。

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

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

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

例子 (Example)

以下代码段提供了使用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()将auto-commit设置为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();

为了更好地理解,让我们研究一下批处理 - 示例代码

↑回到顶部↑
WIKI教程 @2018