When you need to send more than one SQL statement to a database, consider using a JDBC batch mechanism in order to improve execution efficiency.
The batch mechanism for JDBC is primarily concerned with the following methods of statement or PreparedStatement objects:
|--addbatch (String sql): A method of the statement class that can be called multiple times to add multiple SQL statements to the list of commands in the statement object.
These SQL statements are sent to the database for processing at a time when batch processing is performed.
|--addbatch (): A method of the PreparedStatement class that is called multiple times to add several precompiled SQL statements to the list of commands for the PreparedStatement object.
These SQL statements are sent to the database for processing at a time when batch processing is performed.
|--executebatch (): Sends all SQL statements from the statement object or PreparedStatement Object command list to the database for processing.
|--clearbatch (): Clears the current list of SQL commands.
[Java] view plaincopy/* * create table batch_test (id int primary key auto_increment, name varchar (), age int); */ public class batchtest { @Test public void statementbatch () { connection conn = null; statement st = null; String sql_1 = " Insert into batch_test (name, age) values (' coolxing ', 24) "; String sql_2 = "Insert into batch_test" (Name, age) values (' Coolmin ', 22) "; string sql_3 = " Insert into batch_test (name, age) values (' Yong ', 21) "; String sql_4 = "Update batch_test set name= ' Java" where id=1 "; try { conn = Jdbcutils.getconnection (); St = conn.createstatement (); st.addbatch (sql_1); st.addbatch (sql_2); St.addbatch (sql_3); St.addbatch (Sql_4);nbsp; st.executebatch (); st.clearbatch (); } catch (sqlexception e) { e.printstacktrace (); } finally { jdbcutils.release (null, st, conn); } } @Test public void preparedstatementbatch () { Connection conn = null; preparedstatement st = null; String sql = "Insert into batch_test (name, age) VALUES (?, ?) "; try { conn = jdbcutils.getconnection (); [Java] view plaincopy //by opening only one connection st = Conn.preparestatement (SQL); for (int i = 0; i < 10002; i++) { st.setstring (1, "Coolxing_" + i); st.setint (2, i); st.addbatch (); // A outofmemory error is required to prevent the list of commands in the PreparedStatement object from containing too many pending SQL statements,