Home > Database > Mysql Tutorial > How Can PreparedStatement Improve Multi-Row Inserts in MySQL?

How Can PreparedStatement Improve Multi-Row Inserts in MySQL?

DDD
Release: 2024-12-19 21:09:12
Original
965 people have browsed it

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.
            }
        }
    }
}
Copy after login

Additional Resources

For further details on this technique, refer to the following resources:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template