Using batch processing in JDBC to handle a large number of insert data operations

Source: Internet
Author: User
Tags stmt

JDBC uses batch processing to handle large amounts of data

in the JDBC operation, if we need to insert or delete a large amount of data at once, then we can use batch processing. Note here that you need to set the manual commit to false and use statement. Avoid using preparestatement.

  

 

package com.bjsxt.jdbc;

 

import java.sql.Connection;

import Java.sql.DriverManager;

import java.sql.PreparedStatement;

import Java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

 

/**

* Test the basic usage of batch processing

* @author Gao www.sxt.cn

 *

 */

Public class Demo05 {

Public static void Main (string[] args) {

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

try {

//Load driver class

class.forname ("Com.mysql.jdbc.Driver");

conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/testjdbc", "root", "123456");

Conn.setautocommit (FALSE); Set to manual submission

Long start = System.currenttimemillis ();

stmt = Conn.createstatement ();

for (int i=0;i<20000;i++) {

Stmt.addbatch ("INSERT into T_user (username,pwd,regtime) VALUES (' Gao" +i+ "', 666666,now ())");

}

Stmt.executebatch ();

Conn.commit (); Commit a transaction

Long end = System.currenttimemillis ();

System.out.println ("Insert 20,000 data, time-consuming (milliseconds):" + (End-start));

catch (ClassNotFoundException e) {

e.printstacktrace ();

catch (SQLException e) {

e.printstacktrace ();

}finally{

//follow: resultset-->statment-->connection this order of closure. Be sure to write three pieces of Trycatch separately.

try {

if (rs!=null) {

rs.close ();

}

catch (SQLException e) {

e.printstacktrace ();

}

try {

if (stmt!=null) {

stmt.close ();

}

catch (SQLException e) {

e.printstacktrace ();

}

try {

if (conn!=null) {

conn.close ();

}

catch (SQLException e) {

e.printstacktrace ();

}

}

}

}

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.