What is batch updates in Java?

Batch updates in Java refer to the process of grouping multiple updates or database operations into a single batch execution. This can significantly improve performance and efficiency when dealing with large datasets, as it minimizes the number of database calls and reduces the overhead associated with communication between the application and the database.

Using batch updates, developers can execute a set of updates (like insert, update, or delete) as a single command, which means that the database engine will process them all at once. This is especially useful in scenarios where multiple records need to be updated or inserted simultaneously.


// Example of using batch updates in Java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BatchUpdateExample {
    public static void main(String[] args) {
        Connection connection = null; // Assume connection is established

        String sql = "INSERT INTO Employees (name, age, department) VALUES (?, ?, ?)";
        
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            connection.setAutoCommit(false); // Disable auto-commit

            // Adding multiple updates to batch
            preparedStatement.setString(1, "John Doe");
            preparedStatement.setInt(2, 30);
            preparedStatement.setString(3, "Engineering");
            preparedStatement.addBatch();

            preparedStatement.setString(1, "Jane Smith");
            preparedStatement.setInt(2, 25);
            preparedStatement.setString(3, "Human Resources");
            preparedStatement.addBatch();

            // Execute batch
            int[] updateCounts = preparedStatement.executeBatch();
            connection.commit(); // Commit the transaction

            System.out.println("Batch update completed. Rows affected: " + updateCounts.length);
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                if (connection != null) {
                    connection.rollback(); // Rollback on error
                }
            } catch (SQLException rollbackEx) {
                rollbackEx.printStackTrace();
            }
        } finally {
            // Clean up resources
            // Close connection and statement
        }
    }
}
    

Batch updates Java batch processing database updates JDBC batch processing