Batch inserts with addBatch
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Importing a price list or a term's exam results with one INSERT per row can take seconds, because 2000 rows mean 2000 waits for the database. Sending the rows together removes almost all of that waiting.
The cost of one INSERT at a time
A batch is a group of statements that the program collects with addBatch() and sends to the database together with executeBatch(), in one round trip instead of one trip per row.
Running executeUpdate once per row costs one round trip for every row: the request travels to the server, the server replies, and only then does the next row start. For 2000 rows those waits add up.
addBatch, executeBatch and the row counts
For each row, set the parameters and call addBatch() instead of executeUpdate(). Then call executeBatch() once to send them all. Example 1 adds three rows this way.
Example 1 · A batch of three inserts
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.Arrays;import java.util.List;
public class BatchCategories { public static void main(String[] args) throws SQLException { List<String> names = List.of("Grocery", "Toys", "Garden"); String sql = "INSERT INTO categories (name) VALUES (?)"; try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { con.setAutoCommit(false); try (PreparedStatement ps = con.prepareStatement(sql)) { for (String name : names) { ps.setString(1, name); ps.addBatch(); } int[] counts = ps.executeBatch(); System.out.println("Row counts: " + Arrays.toString(counts)); System.out.println("Rows added: " + Arrays.stream(counts).sum()); } con.rollback(); } }}Row counts: [1, 1, 1] Rows added: 3
What this code does
- Each row sets the parameter and calls
addBatch(); nothing is sent untilexecuteBatch(). - The returned
int[]is[1, 1, 1]: each INSERT changed one row. Summing the array counts the rows added.
executeBatch() returns an int[] with one entry per statement, so its length tells you how many statements ran.
Predict the output
What does the batch do?
Read the code and pick what it prints.
Round 1 of 2
Four rows are added, then the batch is sent.
rewriteBatchedStatements and a timing comparison
rewriteBatchedStatements is a MySQL Connector/J URL setting. When it is true, the driver combines the rows of a batch into one multi-row INSERT, which is far faster.
By default the MySQL driver still sends batched rows one after another. Adding rewriteBatchedStatements=true to the URL combines them. Example 2 times 2000 inserts three ways.
Example 2 · Timing: one by one vs batch vs rewrite
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;
public class BatchTiming { static final int N = 2000; static final String SQL = "INSERT INTO categories (name) VALUES (?)";
static Connection open(boolean rewrite) throws SQLException { String url = System.getenv("DB_URL"); if (rewrite) url += (url.contains("?") ? "&" : "?") + "rewriteBatchedStatements=true"; return DriverManager.getConnection(url, System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); }
static long time(Connection con, boolean batch) throws SQLException { long start = System.currentTimeMillis(); try (PreparedStatement ps = con.prepareStatement(SQL)) { for (int i = 0; i < N; i++) { ps.setString(1, "Cat-" + i); if (batch) ps.addBatch(); else ps.executeUpdate(); } if (batch) ps.executeBatch(); } return System.currentTimeMillis() - start; }
public static void main(String[] args) throws SQLException { try (Connection plain = open(false); Connection fast = open(true)) { plain.setAutoCommit(false); fast.setAutoCommit(false); long oneByOne = time(plain, false); plain.rollback(); long batchPlain = time(plain, true); plain.rollback(); long batchFast = time(fast, true); fast.rollback(); System.out.println("One row at a time: " + oneByOne + " ms"); System.out.println("Batch, plain URL: " + batchPlain + " ms"); System.out.println("Batch, rewriteBatchedStatements:" + batchFast + " ms"); } }}One row at a time: 1132 ms Batch, plain URL: 850 ms Batch, rewriteBatchedStatements:93 ms
What this code does
- One INSERT per row is the slowest. A plain batch helps a little, because the driver still sends rows one by one.
- With
rewriteBatchedStatements=truethe driver combines the rows into one statement and the time drops sharply. Your exact milliseconds will differ.
With the flag, executeBatch may report the counts as SUCCESS_NO_INFO (the value -2), because the driver no longer tracks each row separately. That is normal and not an error.
jdbc:mysql://localhost:3306/shoplite?rewriteBatchedStatements=true.Large imports in chunks
Do not add a million rows to one batch: it holds them all in memory and sends one huge statement. Example 3 sends the batch every 100 rows and starts a fresh one.
Example 3 · A large import in chunks
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.Arrays;
public class ChunkedImport { public static void main(String[] args) throws SQLException { String sql = "INSERT INTO products (sku, name, category_id, price, stock) VALUES (?, ?, 5, ?, ?)"; int total = 0; int chunkSize = 100; try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { con.setAutoCommit(false); try (PreparedStatement ps = con.prepareStatement(sql)) { int inChunk = 0; for (int i = 1; i <= 250; i++) { ps.setString(1, "IMP-" + i); ps.setString(2, "Imported book " + i); ps.setBigDecimal(3, new BigDecimal("199.00")); ps.setInt(4, 10); ps.addBatch(); if (++inChunk == chunkSize) { total += Arrays.stream(ps.executeBatch()).sum(); inChunk = 0; } } if (inChunk > 0) total += Arrays.stream(ps.executeBatch()).sum(); } System.out.println("Imported " + total + " products in chunks of " + chunkSize); con.rollback(); } }}Imported 250 products in chunks of 100
What this code does
- After every 100 rows the code runs
executeBatch()and resets the counter, so the batch never grows too large. - The final
if (inChunk > 0)flushes the last 50 rows. Summing each batch's counts gives 250 rows in all.
A chunk of a few hundred to a few thousand rows is a common choice: a bigger chunk uses more memory, and a smaller one sends more trips.
When one row fails: BatchUpdateException
BatchUpdateException is the exception executeBatch() throws when a row of the batch fails. Its getUpdateCounts() array shows which rows worked.
If a row breaks a rule, such as a duplicate value in a unique column, executeBatch() throws a BatchUpdateException. Example 4 inserts three rows, one of them a duplicate.
Example 4 · A failing row and BatchUpdateException
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.BatchUpdateException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.Arrays;import java.util.List;
public class BatchFailure { public static void main(String[] args) throws SQLException { String sql = "INSERT INTO categories (name) VALUES (?)"; try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { con.setAutoCommit(false); try (PreparedStatement ps = con.prepareStatement(sql)) { for (String name : List.of("Toys", "Books", "Garden")) { // "Books" already exists ps.setString(1, name); ps.addBatch(); } ps.executeBatch(); } catch (BatchUpdateException e) { System.out.println("Row counts: " + Arrays.toString(e.getUpdateCounts())); System.out.println("Reason: " + e.getMessage()); con.rollback(); } } }}Row counts: [1, -3, 1] Reason: Duplicate entry 'Books' for key 'categories.uq_categories_name'
What this code does
Booksalready exists, andcategories.nameis unique, so that INSERT fails andexecuteBatch()throws aBatchUpdateException.getUpdateCounts()is[1, -3, 1]:ToysandGardenwere applied (1 each), and-3isStatement.EXECUTE_FAILEDforBooks. The rollback undoes the whole batch.
getUpdateCounts() returns the counts for the rows the driver tried, with Statement.EXECUTE_FAILED (the value -3) for the one that failed. In real code a batch runs inside a transaction (a later lesson), so one bad row rolls the whole batch back and the table is never left half-loaded.
Next step
Check your understanding
10 quick questions