Home >Database >Mysql Tutorial >How Can PreparedStatement Improve Multi-Row Inserts in MySQL?
Optimizing Multi-Row Inserts with PreparedStatement
Initially, inserting rows into a MySQL table using a loop and individual PreparedStatment calls was a common practice. However, to enhance performance, utilizing the MySQL-supported syntax for multi-row insertions is desirable.
Batching with PreparedStatement
A PreparedStatement offers a solution for optimized multi-row inserts through batching. By employing the PreparedStatement#addBatch() method, multiple SQL statements are accumulated in a batch. These statements are then executed simultaneously via PreparedStatement#executeBatch().
The following sample code demonstrates this approach:
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. } } } }
Additional Resources
For further details on this technique, refer to the following resources:
The above is the detailed content of How Can PreparedStatement Improve Multi-Row Inserts in MySQL?. For more information, please follow other related articles on the PHP Chinese website!