Java: Insert multiple rows into MySQL with PreparedStatement

后端 未结 6 1256
后悔当初
后悔当初 2020-11-22 16:28

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)          


        
6条回答
  •  [愿得一人]
    2020-11-22 17:02

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

    Here's a kickoff example:

    public void save(List 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:

    • JDBC tutorial - Using PreparedStatement
    • JDBC tutorial - Using Statement Objects for Batch Updates

提交回复
热议问题