Skip to content

Instantly share code, notes, and snippets.

@sergions80
Last active August 29, 2015 14:16
Show Gist options
  • Save sergions80/2d31f674e5d3b1948657 to your computer and use it in GitHub Desktop.
Save sergions80/2d31f674e5d3b1948657 to your computer and use it in GitHub Desktop.
Batch Insert In Java – JDBC
/*
* This is a simplest solution. Consider a batch size like 1000
* and insert queries in the batches of 1000 queries at a time.
*/
String sql = "insert into employee (name, city, phone) values (?, ?, ?)";
Connection connection = new getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
final int batchSize = 1000;
int count = 0;
for (Employee employee: employees) {
ps.setString(1, employee.getName());
ps.setString(2, employee.getCity());
ps.setString(3, employee.getPhone());
ps.addBatch();
if(++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
ps.close();
connection.close();
/*
* This would be the ideal solution. This avoids SQL
* Injection and also takes care of out of memory issue.
* Check how we have incremented a counter count and once
* it reaches batchSize which is 1000, we call executeBatch().
* /
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment