I need to insert multiple rows into SQL Server database (100 at a time) from my Java code. How can I do this? Currently I am inserting one by one and this does not look efficient.
Asked
Active
Viewed 1.4k times
3 Answers
17
You can use PreparedStatement#addBatch()
to create a batch and executeBatch()
to execute it.
Connection connection = null;
PreparedStatement statement = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement(SQL);
for (int i = 0; i < items.size(); i++) {
Item item = items.get(i);
statement.setString(1, item.getSomeValue());
// ...
statement.addBatch();
if ((i + 1) % 100 == 0) {
statement.executeBatch(); // Execute every 100 items.
}
}
statement.executeBatch();
} finally {
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
See also:

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
in this approach if one record from the batch fails what will happen..? will the records after the failed record be inserted...how do i make sure that except the record that fails all other records be inserted...? – Kaddy Jul 01 '10 at 23:26
-
1That actually depends on the driver used. See [`executeBatch()` javadoc](http://java.sun.com/javase/6/docs/api/java/sql/Statement.html#executeBatch%28%29). – BalusC Jul 02 '10 at 01:06
2
Use a batch.
Check out the addBatch(), executeBatch(), etc. methods of Java's Statement
For a simple example, check here (but I would suggest using a PreparedStatement)

froadie
- 79,995
- 75
- 166
- 235
-
-
@Kaddy - I would recommend doing it on the Java side with a batch using PreparedStatement – froadie Jun 22 '10 at 17:26
1
You can pass one very long string to SQL with multiple inserts as one statement to SQL Server. This won't work if you're doing parameterized queries, though. And concatenated SQL strings are "Generally a Bad Idea."
You might be better off looking at the BULK INSERT command. It has the problem of being rigid about column orders and such. But its WAY FAST!!

Tim Coker
- 6,484
- 2
- 31
- 62
-
-
yeah, its a PITA to write the file and such, but its a good command to be aware of. :) – Tim Coker Jun 22 '10 at 19:11