I. INTRODUCTION 1.1 Concept Note
Batching (Batch)------------> Like a Courier "Can't deliver a single piece of courier"
-batching refers to executing multiple SQL statements in one operation
-Batch processing is much more efficient than one-time execution
1.2 Steps
-batch processing is mainly divided into two steps:
1. Save the SQL statement you want to execute
2. Execute SQL statements
statement and PreparedStatement both support batch operations, and here we only need to master the PreparedStatement batch process
1.3 Methods
void Addbatch ()
-The SQL that will be executed is saved first, not executed first.
-This method is called after all the placeholders have been set
Int[] ExecuteBatch ()
-This method is used to execute the SQL statement, which executes all SQL statements in the batch
-MySQL default batch is off, so we also need to open MySQL batch processing:
Rewritebatchedstatements=true
we need to add the above parameters to the MySQL URL address .
-Note: The low version of the MYSQL-JDBC driver also does not support batch processing, generally in the modification of the use of batch processing, when the query is not used!
Ii. Case Demonstration 2.1 Creating a new data table
CREATE TABLE t_emp ( INTPRIMARYKEY auto_increment, VARCHAR( - ) )
2.2 Writing database operation code at the DAO layer
PackageCom.tyd.batch.dao;Importjava.sql.Connection;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.util.ArrayList;Importjava.util.List; Public classUserdao { Public voidTestbatch () {//inserting 10,000 data into the T_emp table//Prepare two variablesConnection Connection =NULL; PreparedStatement PS=NULL; Try { //Get database connectionconnection=jdbcutil.getconnection (); //Preparing SQL TemplatesString sql = "INSERT into T_emp (NAME) VALUES (?)"; //Get PreparestatementPS =connection.preparestatement (SQL); //create a For loop to set up placeholders for(inti = 0; I < 10000; i++){ //padding placeholdersPs.setstring (1, "EMP" +i); //add to the batch method, call the non-argument, the argument is statement to call! Ps.addbatch (); } //Get a timestamp LongStart =System.currenttimemillis (); //perform batch processingPs.executebatch (); //Get a timestamp LongEnd =System.currenttimemillis (); System.out.println ("Total Cost:" + (end-start)); } Catch(SQLException e) {e.printstacktrace (); }finally{jdbcutil.close (connection, PS,NULL); } }}
2.3 Running in the main method or test class
Public Static void Main (string[] args) { System.out.println ("Start Execution"); Userdao ud=new Userdao (); System.out.println ("execution End"); }
2.4 Validating in the database
SELECT * from T_emp;
Batch processing--database