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