Using JDBC for batch processing

Source: Internet
Author: User
Tags bulk insert

In the actual project development, sometimes need to send a batch of SQL statement execution to the database, should avoid to send execution to the database, and should adopt the batch processing mechanism of JDBC, in order to improve the execution efficiency.

There are two ways in which JDBC implements batching: statement and preparedstatement

I. Using statement to complete batch processing

1. Use the Statement object to add the SQL statement to execute in bulk, as follows:

Statement.addbatch (SQL1); Statement.addbatch (SQL2); Statement.addbatch (SQL3);

2. Execute batch SQL statement:Statement.executeBatch();

3. Clear Batch processing command:Statement.clearBatch();

1.1. Use statement to complete the batch processing example

1. Write the test SQL script to create the table

CREATE TABLE Testbatch (      ID int primary KEY,      name varchar (20));

2. Write the test code as follows:

Package Me.gacl.demo;import Java.sql.connection;import Java.sql.resultset;import java.sql.statement;import Me.gacl.utils.jdbcutils;import org.junit.test;/*** @ClassName: jdbcbatchhandlebystatement* @Description:    Implementing JDBC Batch operations with statement * @author: Aloof Wolf * @date: 2014-9-20 pm 10:05:45**/public class Jdbcbatchhandlebystatement {@Test        public void Testjdbcbatchhandlebystatement () {Connection conn = null;        Statement st = null;        ResultSet rs = null;            try{conn = Jdbcutils.getconnection ();            String SQL1 = "INSERT into Testbatch (id,name) VALUES (1, ' AAA ')";            String sql2 = "INSERT into Testbatch (Id,name) VALUES (2, ' BBB ')";            String sql3 = "INSERT into Testbatch (Id,name) VALUES (3, ' CCC ')";            String Sql4 = "INSERT into Testbatch (id,name) VALUES (4, ' DDD ')";            String sql5 = "Update testbatch set name= ' GaCl ' where id=1";            String sql6 = "INSERT into Testbatch (id,name) VALUES (5, ' FFF ')"; String SQL7 = "DElete from Testbatch where id=2 ";            st = Conn.createstatement ();            Add SQL St.addbatch (SQL1) to be executed in bulk;            St.addbatch (SQL2);            St.addbatch (SQL3);            St.addbatch (SQL4);            St.addbatch (SQL5);            St.addbatch (SQL6);            St.addbatch (SQL7);            Executes a batch SQL statement st.executebatch ();        Clear Batch command St.clearbatch ();        }catch (Exception e) {e.printstacktrace ();        }finally{Jdbcutils.release (Conn, St, RS); }    }}

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: The **sql statement is 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.

For example:

Insert into User (Name,password) VALUES (' AA ', ' 111 '); Insert into User (Name,password) VALUES (' BB ', ' 222 '); Insert into User (Name,password) VALUES (' cc ', ' 333 '); Insert into User (Name,password) VALUES (' dd ', ' 444 ');

Second, the use of PreparedStatement complete batch processing

2.1. Use PreparedStatement to complete the batch processing example

The test code is as follows:

Package Me.gacl.demo;import Java.sql.connection;import Java.sql.preparedstatement;import java.sql.ResultSet;import Me.gacl.utils.jdbcutils;import org.junit.test;/*** @ClassName: jdbcbatchhandlebystatement* @Description: Implementing JDBC Batch operations with Preparestatement * @author: Aloof Wolf * @date: 2014-9-20 pm 10:05:45**/public class  jdbcbatchhandlebypreparestatement {@Test public void testjdbcbatchhandlebypreparestatement () {Long starttime        = 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 (int i=1;i<1000008;i++) {//i=1000-st.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);        } Long Endtime = 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.

Reprinted from: Http://www.tuicool.com/articles/z6vamqi

Using JDBC for batch processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.