There are two ways in which JDBC implements batching:statement and PreparedStatement
First, the use of statement complete batch processing 1.1,
using statement to complete the batch process example
1. Use the Statement object to add the SQL statement to execute in bulk, as follows:
Statement.addbatch (SQL2); Statement. Addbatch (SQL3);
2. Execute batch SQL statement:Statement. ExecuteBatch();
3, Clear Batch processing command:Statement. Clearbatch();
1.2, using Statement.addbatch (SQL) method to achieve the pros and cons of batch processing
Batch processing using Statement.addbatch (SQL):
Pros: You can send multiple different SQL statements to the database.
Disadvantage: SQL statements are not precompiled.
When you send more than one statement to a database, but only a different SQL statement, you need to write a number of SQL statements repeatedly.
Second, the use of PreparedStatement complete batch processing (recommended) 2.1,
using PreparedStatement to complete the batch process example
PackageMe.gacl.demo;Importjava.sql.Connection;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importme.gacl.utils.JdbcUtils;Importorg.junit.Test;/*** @ClassName: jdbcbatchhandlebystatement* @Description: Implementing JDBC Batch operations with Preparestatement *@author: Aloof and Pale wolf * @date: 2014-9-20 pm 10:05:45**/ Public classjdbcbatchhandlebypreparestatement {@Test Public voidtestjdbcbatchhandlebypreparestatement () {LongStartTime =System.currenttimemillis (); Connection Conn=NULL; PreparedStatement St=NULL; ResultSet RS=NULL; Try{conn=jdbcutils.getconnection (); String SQL = "INSERT into Testbatch (id,name) VALUES (?,?)"; St = conn.preparestatement (sql); for(inti=1;i<1000008;i++) {//i=1000St.setint (1, i); St.setstring (2, "AA" +i); St.addbatch (); if(i%1000==0) { st.executebatch (); St.clearbatch (); }} St.executebatch(); } Catch(Exception e) {e.printstacktrace (); }finally{jdbcutils.release (conn, St, RS); } LongEndtime =System.currenttimemillis (); System.out.println ("Program takes time:" + (Endtime-starttime)/1000 + "seconds!! "); }}
2.2, using Preparedstatement.addbatch () method to achieve the advantages and disadvantages of batch processing
Using Preparedstatement.addbatch () to implement batch processing
Advantage: The post-compilation SQL statement is sent with high execution efficiency.
Disadvantage: You can only apply in batches that have the same SQL statement but different parameters. So this form of batching is often used to bulk insert data in the same table, or to bulk update the data for a table.
The content on the JDBC batch is summed up so much.
Using JDBC for batch processing