Open In App

Inserting Records in Batch Using JDBC

Last Updated : 18 Sep, 2025
Comments
Improve
Suggest changes
1 Likes
Like
Report

Batch insertion in JDBC allows you to insert multiple records efficiently in one go, instead of executing individual queries repeatedly. This is achieved using the methods addBatch() and executeBatch().

Before proceeding, ensure you have:

  • A JDBC driver for your database (e.g., MySQL Connector/J for MySQL).
  • The driver .jar file added to your project classpath.
  • A database and table created (example table: emp).

Key Methods for Batch Insertion

1. addBatch()

  • addBatch() adds a set of parameter values to the batch.
  • Each set of values corresponds to one record.

2. executeBatch()

  • executeBatch() executes all accumulated batch updates at once.
  • Returns an int[] array showing how many records were affected by each statement.

SQL Table Creation

Java
create table emp(
    eid varchar(200) unique,
    ename varchar(200)
);

Example:

Java
// Step 1: Importing DB(SQL) classes
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class InsertionBatchExample {

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost/test";
        String user = "root";
        String password = "";

        String sql = "INSERT INTO emp (eid, ename) VALUES (?, ?)";

        try (
            // Step 2: Establish connection
            Connection con = DriverManager.getConnection(url, user, password);
            PreparedStatement pstmt = con.prepareStatement(sql)
        ) {
            // Disable auto-commit for batch processing
            con.setAutoCommit(false);

            final int batchSize = 500; // Commit in batches of 500
            int count = 0;

            // Step 3: Add records in batch
            for (int i = 4000; i <= 4500; i++) {
                pstmt.setString(1, "181FA0" + i);
                pstmt.setString(2, "Employee_" + i);
                pstmt.addBatch();

                count++;

                // Execute batch when batchSize is reached
                if (count % batchSize == 0) {
                    pstmt.executeBatch();
                }
            }

            // Execute remaining records
            pstmt.executeBatch();

            // Commit transaction
            con.commit();

            System.out.println("Batch insertion completed successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Run Program:

out
output

Article Tags :

Explore