Java如何在JDBC中创建批处理更新?
批处理语句可用于在数据库操作中作为一个单元执行多个更新命令。数据库中的该语句不是一个接一个地执行,而是一次执行。在某些情况下,使用批处理更新可能比分别执行命令更有效。
在此示例中,显示了如何创建批处理命令以将一些产品数据插入数据库。
package org.nhooo.example.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JDBCBatchExample { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { //开启自动提交模式 connection.setAutoCommit(false); try (Statement statement = connection.createStatement()) { //和一些批处理将一些产品信息插入 //产品表 statement.addBatch("INSERT INTO products (code, name) " + "VALUE ('P0000006', 'Championship Manager')"); statement.addBatch("INSERT INTO products (code, name) " + "VALUE ('P0000007', 'Transport Tycoon Deluxe')"); statement.addBatch("INSERT INTO products (code, name) " + "VALUE ('P0000008', 'Roller Coaster Tycoon 3')"); statement.addBatch("INSERT INTO products (code, name) " + "VALUE ('P0000009', 'Pro Evolution Soccer')"); //要执行批处理命令,我们必须调用executeBatch() //方法。 int[] updateCounts = statement.executeBatch(); //提交交易 connection.commit(); } catch (SQLException e) { connection.rollback(); e.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>