Java: Insert multiple rows into MySQL with PreparedStatement Java: Insert multiple rows into MySQL with PreparedStatement java java

Java: Insert multiple rows into MySQL with PreparedStatement


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

Here's a kickoff example:

public void save(List<Entity> entities) throws SQLException {    try (        Connection connection = database.getConnection();        PreparedStatement statement = connection.prepareStatement(SQL_INSERT);    ) {        int i = 0;        for (Entity entity : entities) {            statement.setString(1, entity.getSomeProperty());            // ...            statement.addBatch();            i++;            if (i % 1000 == 0 || i == entities.size()) {                statement.executeBatch(); // Execute every 1000 items.            }        }    }}

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:

String myArray[][] = { { "1-1", "1-2" }, { "2-1", "2-2" }, { "3-1", "3-2" } };StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");for (int i = 0; i < myArray.length - 1; i++) {    mySql.append(", (?, ?)");}myStatement = myConnection.prepareStatement(mySql.toString());for (int i = 0; i < myArray.length; i++) {    myStatement.setString(i, myArray[i][1]);    myStatement.setString(i, myArray[i][2]);}myStatement.executeUpdate();