批处理
基本介绍:
1.当需要成批插入或者更新记录时。 可以采用Java的批量更新机制,这一机制允
许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。
2.JDBC的批量处理语句包括下面方法:
addBatch();添加需要批量处理的SQL语句或参数
executeBatch();执行批量处理语句
clearBatch();清空批处理包的语句
3. JDBC连接MySQL时, 如果要使用批处理功能,请再url中加参数:
?rewririteBatchedStatements = true
4.批处理往往和PreparedStatement一起搭配使用,可以既减少编译次数,又减
少运行次数,效率大大提高
传统处理与批处理代码比较:
import com.JDBC.utils.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Batch {
@Test
public void noBatch() throws SQLException {
String sql="insert into dog values(?,?)";
Connection connection = JDBCUtils.getConnection();
PreparedStatement preparedStatement =connection.prepareStatement(sql);
System.out.println("开始执行了");
long start =System.currentTimeMillis();
for (int i=0;i<5000;i++){
preparedStatement.setInt(1,i);
preparedStatement.setString(2,"songdog"+i);
preparedStatement.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println("结束共耗时:"+(end-start));//耗时:18927ms
JDBCUtils.close(null,connection,preparedStatement);
}
@Test
public void Batch() throws SQLException {
String sql="insert into dog values(?,?)";
Connection connection = JDBCUtils.getConnection();
PreparedStatement preparedStatement =connection.prepareStatement(sql);
System.out.println("开始执行了");
long start =System.currentTimeMillis();
for (int i=0;i<5000;i++){
preparedStatement.setInt(1,i);
preparedStatement.setString(2,"songdog"+i);
preparedStatement.addBatch();//将sql语句加入到批处理包中
//装满1000条执行
if((i+1)%1000==0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();//清空掉记录,方便下次装载
}
}
long end = System.currentTimeMillis();
System.out.println("批处理结束共耗时:"+(end-start));//耗时:87ms
JDBCUtils.close(null,connection,preparedStatement);
}
}
addBatch()源码分析:
//addBatch()的源码分析
/*
1.创建ArrayList - elementData=>Object[]
2.elementData=>Object[] 就会存放我们预处理的sql语句
3.当elementData满的时候,就安装1*1.5的方式扩充
4.当添加达到指定的值后,就executeBatch();
5.所以批量处理会减少我们发送sql语句的网络开销,而且减少编译次数,因此效率提高
public void addBatch() throws SQLException{
synchronized(this.checkClosed().getConnectionMutex()){
if(this.batchedArgs == null){
this.batchedArgs = new ArrayList();
}
for(int i= 0;i<this.parameterValues.length;++i){
this.checkAllParameterSet(this.parameterValues[i],this.parameterStreams[i],i);
}
this.batchedArgs.add(new PreparedStatement.BatchParams(this.parameterValues,this.parameterStreams)
}
}
*/