Inserting Multiple Rows into MySQL with PreparedStatement
Often, there's a need to insert multiple rows into a database at once. While traditional methods involving iterating over each row and executing an insert statement can be inefficient, MySQL offers a syntax that allows inserting multiple rows in a single query:
INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...]
Using PreparedStatements for Batching
To optimize this process using Java and PreparedStatements, consider batching, supported by the PreparedStatement class. By creating a batch with addBatch(), you can execute it as a group using executeBatch().
Code Example
The following example demonstrates how to batch insertions:
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(); } } } }
Batch Execution Optimization
Batching is executed every 1000 items to avoid potential limitations of JDBC drivers or databases.
Additional Resources
The above is the detailed content of How Can I Efficiently Insert Multiple Rows into MySQL Using Java PreparedStatements?. For more information, please follow other related articles on the PHP Chinese website!