サーチ…


前書き

文のバッチ処理は、複数の文を1つの単位(通常のjava.sql.Statement )として実行するか、複数のパラメータ値セットを持つ単一の文( java.sql.PreparedStatement )を実行することです。

備考

ステートメントのバッチ処理により、プログラムは関連するステートメントを収集するか、プリペアドステートメント関連のパラメーター値セットの場合は、単一の実行としてデータベースサーバーに送信することができます。

ステートメントバッチ処理の利点には、パフォーマンスの向上が含まれます。これらのパフォーマンス上の利点がどのように達成されるかは、ドライバーとデータベースのサポートによって異なりますが、以下が含まれます。

  • 1つのコマンドですべてのステートメント(またはすべての値セット)を送信する
  • 1つの大きなステートメントのように実行できるようにステートメントを書き直す

PreparedStatementを使用したバッチ挿入

java.sql.PreparedStatementを使用したバッチ実行では、そのパラメータに複数の値セットを持つ単一のDML文を実行できます。

この例では、insert文を準備し、複数の行をバッチに挿入する方法を示します。

Connection connection = ...; // obtained earlier
connection.setAutoCommit(false); // disabling autoCommit is recommend for batching
int orderId = ...; // The primary key of inserting and order
List<OrderItem> orderItems = ...; // Order item data

try (PreparedStatement insert = connection.prepareStatement(
        "INSERT INTO orderlines(orderid, itemid, quantity) VALUES (?, ?, ?)")) {
    // Add the order item data to the batch
    for (OrderItem orderItem : orderItems) {
        insert.setInt(1, orderId);
        insert.setInt(2, orderItem.getItemId());
        insert.setInt(3, orderItem.getQuantity());
        insert.addBatch();
    }

    insert.executeBatch();//executing the batch 
}

connection.commit();//commit statements to apply changes 

ステートメントを使用したバッチ実行

java.sql.Statementを使用したバッチ実行では、複数のDML文( updateinsertdelete )を一度に実行できます。これは、単一のステートメント・オブジェクトを作成し、実行するステートメントを追加し、バッチを1つとして実行することによって実現されます。

Connection connection = ...; // obtained earlier
connection.setAutoCommit(false); // disabling autocommit is recommended for batch execution

try (Statement statement = connection.createStatement()) {
    statement.addBatch("INSERT INTO users (id, username) VALUES (2, 'anna')");
    statement.addBatch("INSERT INTO userrole(userid, rolename) VALUES (2, 'admin')");
    
    statement.executeBatch();//executing the batch 
}

connection.commit();//commit statements to apply changes 

注意:

statement.executeBatch();返された値を保持するためにint[]を返します。このようにバッチを実行することができます:

int[] stmExc = statement.executeBatch();//executing the batch 


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow