北大青鸟南京泰思特鼓楼校区·华东区专业软件测试培训学校_免费咨询电话 400-888-6020
您的位置:首页 - 技术通道 - 专业知识
返回首页
使用JDBC插入大量数据的性能测试
2010/2/22  发布人:qiantai
使用jdbc向数据库插入100000条记录,分别使用statement,PreparedStatement,及PreparedStatement+批处理3种方式进行测试
  1、使用statement插入100000条记录
  public void exec(Connection conn){
  try {
  Long beginTime = System.currentTimeMillis();
  conn.setAutoCommit(false);//设置手动提交
  Statement st = conn.createStatement();
  for(int i=0;i<100000;i++){
  String sql="insert into t1(id) values ("+i+")";
  st.executeUpdate(sql);
  }
  Long endTime = System.currentTimeMillis();
  System.out.println("st:"+(endTime-beginTime)/1000+"秒");//计算时间
  st.close();
  conn.close();
  } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }
  2、使用PreparedStatement对象
  public void exec2(Connection conn){
  try {
  Long beginTime = System.currentTimeMillis();
  conn.setAutoCommit(false);//手动提交
  PreparedStatement pst = conn.prepareStatement("insert into t1(id) values (?)");
  for(int i=0;i<100000;i++){
  pst.setInt(1, i);
  pst.execute();
  }
  conn.commit();
  Long endTime = System.currentTimeMillis();
  System.out.println("pst:"+(endTime-beginTime)/1000+"秒");//计算时间
  pst.close();
  conn.close();
  } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }
3、使用PreparedStatement + 批处理
  public void exec3(Connection conn){
  try {
  conn.setAutoCommit(false);
  Long beginTime = System.currentTimeMillis();
  PreparedStatement pst = conn.prepareStatement("insert into t1(id) values (?)");
  for(int i=1;i<=100000;i++){
  pst.setInt(1, i);
  pst.addBatch();
  if(i%1000==0){//可以设置不同的大小;如50,100,500,1000等等
  pst.executeBatch();
  conn.commit();
  pst.clearBatch();
  }
  }
  Long endTime = System.currentTimeMillis();
  System.out.println("pst+batch:"+(endTime-beginTime)/1000+"秒");
  pst.close();
  conn.close();
  } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }
  在Oracle 10g中测试,结果:
  1、使用statement耗时142秒;
  2、使用PreparedStatement耗时56秒;
  3、使用PreparedStatement + 批处理耗时:
  a.50条插入一次,耗时5秒;
  b.100条插入一次,耗时2秒;
  c.1000条以上插入一次,耗时1秒;
  通过以上可以得出结论,在使用jdbc大批量插入数据时,明显使用第三种方式(PreparedStatement + 批处理)性能更优。
  当使用sqlserver 2000进行测试时,第三种方式最少耗时5秒,从这方面可以看出Oracle在处理大量数据时,明显性能更强。
 
首页 | 走进校区 | 培训课程 | 师资力量 | 行业资讯 | 学员天地 | 就业中心 | 在线报名 | 联系我们 | 友情链接
南京北大青鸟泰思特鼓楼校区|南京软件测试职业培训学校|南京软件人才培养基地|江苏软件测试联盟
地址:南京市中山北路26号新晨国际大厦14层 报名咨询电话:025-83240832 全国免费电话:400-888-6020
版权所有:2008-2010 北大青鸟南京软件测试 苏ICP备07033297号
在线客服
在线客服系统