private void function1(List<Test> list){  
SqlMapClient client = super.getSqlMapClient();  
Connection conn = null;  
try{   
  client.startTransaction();   
  conn = client.getCurrentConnection();   
  conn.setAutoCommit(false);   
  PreparedStatement ps = null;   
  ps = conn.prepareStatement("insert into test
      (t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15) values
      (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");   
  for(int i = 0; i<list.size(); i++){    
    Test t = list.get(i);    
    ps.setString(1, t.getT1());    
    ps.setString(2, t.getT2());    
    ps.setString(3, t.getT3());    
    ps.setString(4, t.getT4());    
    ps.setString(5, t.getT5());    
    ps.setString(6, t.getT6());    
    ps.setString(7, t.getT7());    
    ps.setString(8, t.getT8());    
    ps.setString(9, t.getT9());    
    ps.setString(10, t.getT10());    
    ps.setString(11, t.getT11());    
    ps.setString(12, t.getT12());    
    ps.setString(13, t.getT13());    
    ps.setString(14, t.getT14());    
    ps.setString(15, t.getT15());    
    ps.execute();   
  }   
  conn.commit();   
  client.commitTransaction();  
}catch(SQLException e){   
  e.printStackTrace();   
  try {    
    conn.rollback();   
  } catch (SQLException e1) {    
    e1.printStackTrace();   
  }  
}finally{   
  try {    
    client.endTransaction();   
  } catch (SQLException e) {    
    e.printStackTrace();   
  }  

}function1在处理10000条数据入库时用了3S,效率高。
其可靠性强吗? 这个语句中的conn = client.getCurrentConnection();
能够可靠的取得conn实例吗,api上面说这个方法在一定条件下回返回null,
这个条件是什么样的呢?还有就是conn我不关闭它会回答连接池中吗? private void function2(List<Test> list){    
SqlMapClient client = super.getSqlMapClient();  
try {   
  client.startTransaction();   
  client.startBatch();     
  for(int i = 0; i<list.size(); i++){    
    client.insert("TreeNode.test", list.get(i));   
  }   // 执行批处理               
  client.executeBatch();
  client.commitTransaction();    
} catch (SQLException e) {   
  e.printStackTrace();  
} finally {    
  try {    
    client.endTransaction();   
  } catch (SQLException e) {    
    e.printStackTrace();   
  }  

}function2在处理10000条数据入库时用了11s-12s;
效率较低请教function2有优化方案吗?
综上,function1好还是function2好?

解决方案 »

  1.   

    使用PreparedStatement + 批处理方式无疑是最快的,它可以减少和SQL引擎交互的次数,再次提高效率,相似语句只编译一次,减少编译次数。提高了安全性(阻止了SQL注入),但是你在批处理的时候要做个阀值,比如当批量数据达到200的时候执行一次批处理executeBatch();提交以后再clearBatch();不同的数据库对这个阀值有不同的要求一般50 100 500 1000,楼主要自己去试一试,其他方式我并不推荐,ibatIS批处理会比hibernate高一点,对于这种效率而言,任何都比不上jdbc高,我还是觉得你用jdbc做好一点,另外数据库连接池一定要回收,不要忘了关,否则会导致资源耗尽,系统崩溃!
      

  2.   

    function2在处理10000条数据入库时用了11s-12s;真让人不解
      

  3.   

    这个问题还没结贴么?
    fuction2 插入速度和 JDBC 差不多~
    你只需要在循环里面加一个 if(i%300 == 0) client.executeBatch();
    我想这样 速度就差不多了~
    尽量用框架性质的玩意,以后方便改代码