Statement execute () and other methods can only execute one SQL statement at a time. If Multiple SQL statements are to be executed at the same time, you can use addbatch () the method will only contain the SQL statement and then execute the executebatch () method. In this way, multiple SQL statements are executed in one method call to improve the execution efficiency.
To ensure the success or failure of all these statements, you should place the batch processing in the transaction:
Try {
Conn. setautocommite (false); // set Automatic commit transaction to false
Statement stmt = conn. createstatement ();
Stmt. addbatch ("…"); // Add an SQL statement
Stmt. addbatch ("…"); // Add an SQL statement
...
Stmt.exe cutebatch (); // execute batch processing
Conn. Commit (); // submit the transaction
} Catch (sqlexception e ){
Try {
Conn. rollback (); // roll back the transaction
} Catch (sqlexceptione1 ){
E 1. printstacktrace ();
}
E. printstacktrace ();
} Finally {
Try {
Conn. setautocommit (true); // set Automatic commit transaction to true
} Catch (sqlexceptione ){
E. printstacktrace ();
}
// Close the resource
...
}
You can also use preparedstatement for batch processing:
Try {
// Start the transaction ------ set the automatic commit transaction to false
Conn. setautocommit (false );
Pstmt = conn. preparedstatement (SQL );
Pstmt. setxxx (1 ,...); // Assign a placeholder Value
...
// Add these operations to batch processing
Pstmt. addbatch ();
Pstmt. setxxx (1 ,...); // Assign a placeholder Value
...
// Add these operations to batch processing
Pstmt. addbatch ();
Pstmt.exe cutebatch (); // execute batch processing
// Submit the transaction
Conn. Commit ();
} Catch (sqlexception e ){
// Roll back the transaction ------- cancel all operations
Try {
Conn. rollback ();
} Catch (sqlexceptione1 ){
E 1. printstacktrace ();
}
E. printstacktrace ();
} Finally {
// Close the transaction ----- set the automatic commit transaction to true
Try {
Conn. setautcommit (true );
} Catch (sqlexceptione ){
E. printstracktrace ();
}
// Close the resource
...
}
The statements executed in batch processing can only be update statements (insert, delete, and update). Otherwise, an exception is thrown.