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 ();
}
}
}
}