使用 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