当向数据库中添加大量的数据时,需要用到批处理。
不用批处理时,插入的效率特别的慢。
这里用到了批处理和预编译sql两个联合,这样的效率会更高
注意:PreparedStatement对象的批处理操作调用的是executeBatch()方法,而不是execute()方法或者executeUpdate()方法
首先,要关闭数据库连接的自动提交。否则就不叫批处理了。
connect.setAutoCommit(false);
然后,判断该数据库是否支持批更新。
DatabaseMetaData dbmData = connect.getMetaData();
//...
if (dbmData.supportsBatchUpdates())
{
//使用Statement创建批处理
statement.addBatch("你的SQL语句");
//根据需要添加多条批处理
statement.addBatch("你的SQL语句");
//获得批处理的结果
int[] uCounts = statement.executeBatch();
//等全部添加好了之后,可以一次性递交了。
connect.commit();
//使用PreparedStatement进行批处理
PreparedStatement psStatement = connect.prepareStatement("你的SQL语句(?)");
psStatement.setString(1,"Jennie");
psStatement.addBatch();
//根据需要添加多条批处理语句
psStatement.setString(1,"Tom");
psStatement.addBatch();
//获得批处理的结果
int[] uCounts = psStatement.executeBatch();
//和上面一样可以一次性执行
connect.commit();
//使用CallableStatement进行批处理
CallableStatement cStatement = connect.prepareCall("{call 你的存储过程(?))");
cStatement.setString(1,"Jennie");
cStatement addBatch();
//根据需要添加多条批处理语句
cStatement.setString(1,"Tom");
cStatement.addBatch();
//获得批处理的结果
int[] uCounts = cStatement.executeBatch();
//和上面一样可以一次性执行
connect.commit();
}
最后可以通过捕获 BatchUpdateException 异常的getUpdateCounts()方法,返回的int[]值,来获得每一条批处理的处理数量。
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);
}
}