Batch Processing in Java

Introduction

In many Java applications, you need to execute multiple SQL statements at once. For example, importing thousands of employee records, processing online orders, updating product prices, or generating payroll reports may require executing hundreds or even millions of database operations.

If each SQL statement is sent to the database individually, the application makes multiple network calls, increasing execution time and reducing performance.

To solve this problem, JDBC provides Batch Processing, which groups multiple SQL statements into a single batch and sends them to the database together. This significantly improves performance by reducing network overhead and minimizing database communication.

What is Batch Processing?

Batch Processing is a JDBC feature that allows multiple SQL statements to be grouped into a batch and executed together instead of executing each statement separately.

Rather than sending one SQL statement at a time, JDBC collects multiple statements and sends them to the database in a single request.

This approach:

  • Improves performance
  • Reduces network traffic
  • Minimizes database communication
  • Increases application efficiency

Why Use Batch Processing?

Suppose you need to insert 10,000 employee records.

Without batch processing:


Insert Record 1
Send to Database

Insert Record 2
Send to Database

Insert Record 3
Send to Database
.......

The application performs thousands of database calls.

With batch processing:


Insert Record 1
Insert Record 2
Insert Record 3
...
Insert Record 10000
↓
Send One Batch to Database

Only one or a few database requests are required, making the operation much faster.

How Batch Processing Works

The basic workflow is:

  1. Create a database connection.
  2. Create a Statement or PreparedStatement.
  3. Add SQL statements to the batch using addBatch().
  4. Execute the entire batch using executeBatch().
  5. Optionally commit the transaction.
  6. Clear the batch using clearBatch().
  7. Close all resources.

Sample Database

Create the database.


CREATE DATABASE company;

Use the database.


USE company;

Create the employee table.


CREATE TABLE employee(
    id INT PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(50),
    salary DOUBLE
);

Batch Processing Using Statement

The Statement interface can execute multiple SQL statements in a batch.

Example


import java.sql.*;
public class StatementBatchExample {
    public static void main(String[] args) {
        try {
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/company",
                    "root",
                    "password");
            Statement stmt = con.createStatement();
            stmt.addBatch(
                "INSERT INTO employee VALUES(101,'Rahul','IT',55000)");
            stmt.addBatch(
                "INSERT INTO employee VALUES(102,'Amit','HR',45000)");
            stmt.addBatch(
                "INSERT INTO employee VALUES(103,'Neha','Finance',65000)");
            int[] result = stmt.executeBatch();
            System.out.println("Records Inserted: " + result.length);
            stmt.close();
            con.close();
        } catch(Exception e){
            e.printStackTrace();
       }
    }
}

Output

Records Inserted: 3

Batch Processing Using PreparedStatement

Using PreparedStatement is the preferred approach because it supports parameterized queries and provides better security.

Example


import java.sql.*;
public class PreparedStatementBatchExample {
    public static void main(String[] args) 
        try {
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/company",
                    "root",
                    "password");
            String sql =
                "INSERT INTO employee VALUES(?,?,?,?)";
            PreparedStatement ps =
                    con.prepareStatement(sql);
            ps.setInt(1,101);
            ps.setString(2,"Rahul");
            ps.setString(3,"IT");
            ps.setDouble(4,55000);
            ps.addBatch();
            ps.setInt(1,102);
            ps.setString(2,"Amit");
            ps.setString(3,"HR");
            ps.setDouble(4,45000);
            ps.addBatch();
            ps.setInt(1,103);
            ps.setString(2,"Neha");
            ps.setString(3,"Finance");
            ps.setDouble(4,65000);
            ps.addBatch();
            int[] result = ps.executeBatch();
            System.out.println(result.length +
                    " Records Inserted.");
            ps.close();
            con.close();
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

Output

3 Records Inserted.

Batch Processing with Transactions

Batch processing is often combined with transactions to ensure data consistency.

Example


Connection con = DriverManager.getConnection(
        url,
        username,
        password);
con.setAutoCommit(false);
PreparedStatement ps =
       con.prepareStatement(sql);
ps.addBatch();
ps.addBatch();
ps.addBatch();
ps.executeBatch();
con.commit();
If an error occurs, roll back the transaction.
con.rollback();

This ensures that either all SQL statements are executed successfully or none are applied.

Common Methods Used in Batch Processing

Method Description
addBatch() Adds a SQL statement or parameter set to the batch
executeBatch() Executes all statements in the batch
clearBatch() Removes all statements from the current batch
commit() Permanently saves changes to the database
rollback() Reverts changes if an error occurs
setAutoCommit(false) Disables automatic transaction commits

Batch Processing Workflow


  Java Application
        │
        ▼
 Create Connection
        │
        ▼
Create Statement / PreparedStatement
        │
        ▼
  Add SQL Statements
        │
        ▼
    addBatch()
        │
        ▼
  executeBatch()
        │
        ▼
    Database
        │
        ▼
  Commit / Rollback

Batch Processing vs Normal Execution

Feature Normal Execution Batch Processing
Database Calls Many Few
Performance Slower Faster
Network Traffic High Low
Large Data Processing Less Efficient Highly Efficient
Enterprise Applications Limited Recommended

Advantages of Batch Processing

Batch Processing offers several advantages:

  • Improves application performance.
  • Reduces network overhead.
  • Executes multiple SQL statements efficiently.
  • Saves database processing time.
  • Works well with transactions.
  • Suitable for processing large datasets.
  • Supports both Statement and PreparedStatement.
  • Widely used in enterprise applications.

Real-life Example

Consider a Payroll Management System.

At the end of each month, the system must update the salaries of thousands of employees.

Instead of executing one UPDATE statement for each employee, the application groups all updates into a batch and sends them to the database together.

Other common use cases include:

  • Student result processing
  • Product catalog imports
  • Order processing
  • Banking transactions
  • Data migration
  • Inventory updates
  • Bulk email logging
  • Customer data synchronization

Best Practices

Follow these best practices when using Batch Processing:

📖
Best Practices:
  • Prefer PreparedStatement over Statement.
  • Disable auto-commit for large batches and manage transactions manually.
  • Commit data only after successful batch execution.
  • Split extremely large datasets into smaller batches (for example, 500–1000 records) to avoid excessive memory usage.
  • Close all JDBC resources using try-with-resources whenever possible.
  • Handle BatchUpdateException separately to identify failed statements.
  • Monitor batch size to balance memory usage and performance.

Common Mistakes

Avoid these common mistakes:

  • Forgetting to call executeBatch().
  • Not committing transactions when auto-commit is disabled.
  • Ignoring exceptions during batch execution.
  • Using very large batches that consume excessive memory.
  • Forgetting to clear the batch with clearBatch() before reusing the statement.
  • Not closing database resources.
  • Using Statement with dynamic user input instead of PreparedStatement.
  • Assuming every statement in the batch always succeeds.

Conclusion

Batch Processing is an important JDBC feature that significantly improves the performance of Java applications by executing multiple SQL statements together. It is especially useful when working with large datasets, such as bulk inserts, updates, or deletes.

For the best results, use PreparedStatement with Batch Processing, manage transactions explicitly using commit() and rollback(), and process large datasets in manageable batch sizes. By following these practices, you can build fast, reliable, and scalable database applications suitable for enterprise environments.

Related Java Tutorials