Skip to content
Advertisement

Java: Insert multiple rows into MySQL with PreparedStatement

I want to insert multiple rows into a MySQL table at once using Java. The number of rows is dynamic. In the past I was doing…

JavaScript

I’d like to optimize this to use the MySQL-supported syntax:

JavaScript

but with a PreparedStatement I don’t know of any way to do this since I don’t know beforehand how many elements array will contain. If it’s not possible with a PreparedStatement, how else can I do it (and still escape the values in the array)?

Advertisement

Answer

You can create a batch by PreparedStatement#addBatch() and execute it by PreparedStatement#executeBatch().

Here’s a kickoff example:

JavaScript

It’s executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.

See also:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement