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...
for (String element : array) {
myStatement.setString(1, element[0]);
myStatement.setString(2, element[1]);
myStatement.executeUpdate();
}
I'd like to optimize this to use the MySQL-supported syntax:
INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...]
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)?
You can create a batch by
PreparedStatement#addBatch()
and execute it byPreparedStatement#executeBatch()
.Here's a kickoff example:
It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.
See also:
When MySQL driver is used you have to set connection param
rewriteBatchedStatements
to true( jdbc:mysql://localhost:3306/TestDB?**rewriteBatchedStatements=true**)
.With this param the statement is rewritten to bulk insert when table is locked only once and indexes are updated only once. So it is much faster.
Without this param only advantage is cleaner source code.
If you can create your sql statement dynamically you can do following workaround:
In case you have auto increment in the table and need to access it.. you can use the following approach... Do test before using because getGeneratedKeys() in Statement because it depends on driver used. The below code is tested on Maria DB 10.0.12 and Maria JDBC driver 1.2
Remember that increasing batch size improves performance only to a certain extent... for my setup increasing batch size above 500 was actually degrading the performance.
we can be submit multiple updates together in JDBC to submit batch updates.
we can use Statement, PreparedStatement, and CallableStatement objects for bacth update with disable autocommit
addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate
here addBatch() method adds a set of statements or parameters to the current batch.
@Ali Shakiba your code needs some modification. Error part:
Updated code: