How do I create a batch update in JDBC?

A batch statement can be used to execute multiple update commands as single unit in a database manipulation. This statement in the database is not executed one by one but as a single execution instead. In some cases, using a batch update can be more efficient than to execute the commands separately.

In this example, you are shown how to create a batch command to insert some products into a database table.

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;

public class JDBCBatchExample {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

            // Turn of the auto-commit mode

            try (Statement statement = connection.createStatement()) {
                // And some batch to insert some product information into
                // the product table
                statement.addBatch("INSERT INTO product (code, name) " +
                                   "VALUE ('P0000006', 'Championship Manager')");
                statement.addBatch("INSERT INTO product (code, name) " +
                                   "VALUE ('P0000007', 'Transport Tycoon Deluxe')");
                statement.addBatch("INSERT INTO product (code, name) " +
                                   "VALUE ('P0000008', 'Roller Coaster Tycoon 3')");
                statement.addBatch("INSERT INTO product (code, name) " +
                                   "VALUE ('P0000009', 'Pro Evolution Soccer')");

                // To execute a batch command, we must call the executeBatch()
                // method.
                int[] updateCounts = statement.executeBatch();
                System.out.println("updateCounts = " + Arrays.toString(updateCounts));

                // Commit our transaction
            } catch (SQLException e) {
        } catch (SQLException e) {

Maven Dependencies


Maven Central