Batch Inserts with PreparedStatement
Fast recall
Quick revision
Core answer
Whether you can write a correct batched-insert loop.
Calling executeUpdate inside the loop instead of addBatch, or never committing.
Flush every N rows and commit once; handle rollback on failure.
Interview-ready guide
Interview answer
For example, insert 10,000 audit rows in chunks of 500: bind two values, addBatch, execute/clear each 500, then commit the transaction if all chunks belong to one atomic unit. For a restartable import, committing each validated chunk may be a better requirement than rolling back all 10,000 rows.
Batch Inserts with PreparedStatement
Direct Answer
Reuse one PreparedStatement, bind each row, call addBatch(), and periodically call executeBatch(). A transaction can make a chosen batch atomic and avoid committing each row separately. The correct commit and chunk size depends on rollback needs, memory, locks, log growth, driver limits, and database capacity; one enormous batch and one commit are not always best.
Code Example
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
con.setAutoCommit(false);
try (PreparedStatement ps = con.prepareStatement(sql)) {
int n = 0;
for (User u : users) {
ps.setString(1, u.name());
ps.setString(2, u.email());
ps.addBatch(); // queue
if (++n % 1000 == 0) ps.executeBatch(); // flush every 1000
}
ps.executeBatch(); // remaining
con.commit();
} catch (SQLException e) {
con.rollback();
throw e;
} finally {
con.setAutoCommit(true);
}
Common Mistakes & Pitfalls
executeUpdatein the loop: defeats batching — useaddBatch.- Re-preparing per row: prepare once outside the loop.
- No commit / auto-commit on: each item commits separately.
- One enormous batch: flush every N rows to bound memory.
Check your understanding
Answer these without looking back at the article.
- Why flush a batch every N rows?
- What happens if you call executeUpdate inside the loop?
- How does a transaction affect batch performance?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.