Performing Batch Updates Using Statement

Batch updates in JDBC are used to execute multiple SQL statements as a single group or batch. The Statement interface provides the addBatch() method to add multiple INSERT, UPDATE, or DELETE statements to a batch. The executeBatch() method executes all the SQL statements in the batch and returns an integer array containing the number of affected rows for each statement. Batch processing can improve performance because multiple database operations can be sent to the database together instead of executing them individually.

Program: Performing Batch Updates Using Statement

This program inserts multiple employee records into the employee table using a JDBC batch. The addBatch() method adds each INSERT statement to the batch, and executeBatch() executes all the statements together.

import java.sql.*;

public class StatementBatchExample {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/jdbc_demo";
        String username = "root";
        String password = "password";

        try {
            Connection con =
                    DriverManager.getConnection(
                            url, username, password);

            Statement stmt = con.createStatement();

            // Add SQL statements to the batch
            stmt.addBatch(
                "INSERT INTO employee " +
                "(employee_id, employee_name, department, salary) " +
                "VALUES (107, 'Suresh', 'IT', 45000)"
            );

            stmt.addBatch(
                "INSERT INTO employee " +
                "(employee_id, employee_name, department, salary) " +
                "VALUES (108, 'Anita', 'HR', 47000)"
            );

            stmt.addBatch(
                "INSERT INTO employee " +
                "(employee_id, employee_name, department, salary) " +
                "VALUES (109, 'Kiran', 'Finance', 52000)"
            );

            // Execute the batch
            int[] results = stmt.executeBatch();

            System.out.println("Batch executed successfully.");

            for (int i = 0; i < results.length; i++) {
                System.out.println(
                    "Statement " + (i + 1) +
                    ": " + results[i] +
                    " row affected."
                );
            }

            stmt.close();
            con.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
Execution and Output:

PS D:\test> javac -classpath ".;D:\test\mysql-connector.jar" StatementBatchExample.java
PS D:\test> java -classpath ".;D:\test\mysql-connector.jar" StatementBatchExample
Batch executed successfully.
Statement 1: 1 row affected.
Statement 2: 1 row affected.
Statement 3: 1 row affected.Code language: CSS (css)
Scroll to Top