JDBC批量处理

批处理允许将相关的SQL语句组合成一个批处理和一个调用数据库提交。

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

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

  • 声明addBatch()方法,PreparedStatement和CallableStatement用于各个语句添加到批处理。executeBatch()将用于启动所有组合在一起的语句的执行。

  • executeBatch()将返回一个整数数组,数组中的每个元素代表了各自的更新语句的更新计数。

  • 可以添加语句批量处理,可以用theclearBatch()方法删除它们。此方法删除所有已添加的addBatch()方法的语句。但是,不能有选择性地选择要删除的语句。

 

批处理和Statement对象:

下面是步骤,使用批处理使用说明书对象的典型顺序:

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

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

  • 添加任意多个到批量使用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();

为了更好地理解,建议学习研究JDBC批处理用Statement对象示例代码.

 

批处理使用prepareStatement结果对象:

下面是步骤,使用批处理用prepareStatement结果对象的典型顺序:

  • 创建SQL语句的占位符。

  • 使用任一prepareStatement()方法创建prepareStatement结果对象。

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

  • 添加任意多个批量使用addBatch SQL语句(上创建语句对象)的方法。

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

  • 最后,提交使用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();

为了更好地理解,建议学习研究实例代码.