当向数据库中添加大量的数据时,这是需要用到批处理。不用批处理时,插入的效率特别的慢。这里用到了批处理和预编译sql两个联合,这样的效率会更高
package com.an.jdbc.exer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import org.junit.Test;
import com.an.jdbc.utils.JDBCUtils;
public class TestBatch {
/*
* 不是用批处理向数据库插入50000条记录,特别的慢
*/
@Test
public void test() throws Exception{
String sql = "insert into admin values(null,?,?)";
Connection connection = JDBCUtils.getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
for(int i=0;i<50000;i++){
ps.setString(1, "an"+i);
ps.setString(2, "0000");
ps.executeUpdate();
}
JDBCUtils.closeConnection(null, ps, connection);
}
/**
* 用批处理向数据库添加5000条数据
* @throws Exception
*/
@Test
public void test1() throws Exception{
String sql = "insert into admin values(null,?,?)";
Connection connection = JDBCUtils.getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
for(int i=1;i<=50000;i++){
ps.setString(1, "an"+i);
ps.setString(2, "0000");
ps.addBatch();//将sql语句添加到批处理包(将苹果装到框中)
if(i % 1000 == 0){
ps.executeBatch();//执行批处理包的所有语句(将框运到教室)
ps.clearBatch();//清空批处理包的sql语句(卸苹果)
}
}
JDBCUtils.closeConnection(null, ps, connection);
}
}