Java Academy Logo

Java Academy

JDBC Batch Processing

Batch processing groups multiple SQL statements into a single round-trip to the database, significantly improving performance for bulk inserts, updates, and deletes.

Batch Insert Example

String sql = "INSERT INTO logs (message, level, created_at) VALUES (?, ?, ?)";
conn.setAutoCommit(false);
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    for (LogEntry entry : entries) {
        ps.setString(1, entry.getMessage());
        ps.setString(2, entry.getLevel());
        ps.setTimestamp(3, Timestamp.from(entry.getCreatedAt()));
        ps.addBatch();
    }
    int[] results = ps.executeBatch();
    conn.commit();
}

Performance Tips

  • Use batches of 500-1000 rows, not millions at once.
  • Disable auto-commit during batch operations.
  • Consider COPY (PostgreSQL) or LOAD DATA (MySQL) for very large imports.
  • Monitor memory — large batches consume heap.

Frequently Asked Questions

Batch vs single inserts — how much faster?

Batching can be 10-50x faster than individual inserts due to reduced network round-trips and database parsing overhead.

Continue Learning