Home > Java > javaTutorial > How Can I Efficiently Insert Multiple Rows into MySQL Using Java PreparedStatements?

How Can I Efficiently Insert Multiple Rows into MySQL Using Java PreparedStatements?

Barbara Streisand
Release: 2024-12-01 01:59:14
Original
302 people have browsed it

How Can I Efficiently Insert Multiple Rows into MySQL Using Java PreparedStatements?

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')[, ...]
Copy after login

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();
            }
        }
    }
}
Copy after login

Batch Execution Optimization

Batching is executed every 1000 items to avoid potential limitations of JDBC drivers or databases.

Additional Resources

  • [JDBC Tutorial - Using PreparedStatement](https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html)
  • [JDBC Tutorial - Using Statement Objects for Batch Updates](https://docs.oracle.com/javase/tutorial/jdbc/basics/batchupdates.html)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template