使用 Statement 批量执行

使用 java.sql.Statement 批量执行允许你一次执行多个 DML 语句(updateinsertdelete)。这是通过创建单个语句对象,添加要执行的语句,然后将批处理作为一个执行来实现的。

Connection connection = ...; // obtained earlier
connection.setAutoCommit(false); // disabling autocommit is recommended for batch execution

try (Statement statement = connection.createStatement()) {
    statement.addBatch("INSERT INTO users (id, username) VALUES (2, 'anna')");
    statement.addBatch("INSERT INTO userrole(userid, rolename) VALUES (2, 'admin')");
    
    statement.executeBatch();//executing the batch 
}

connection.commit();//commit statements to apply changes 

注意:

statement.executeBatch(); 将返回 int[] 以保存返回值,你可以像这样执行你的批处理:

int[] stmExc = statement.executeBatch();//executing the batch