使用 Statement 批量執行
使用 java.sql.Statement
批量執行允許你一次執行多個 DML 語句(update
,insert
,delete
)。這是通過建立單個語句物件,新增要執行的語句,然後將批處理作為一個執行來實現的。
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