用Java向數據庫中插入大量數據時的優化


注:本文來自http://geeklee.iteye.com/blog/1160949
  • 使用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) {   
   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) {   
   e.printStackTrace();   
  }   
  
}   
3、使用PreparedStatement + 批處理
public void exec3(Connection conn){   
  try {   
   conn.setAutoCommit(false);   
   Long beginTime = System.currentTimeMillis();   
   //構造預處理statement  
   PreparedStatement pst = conn.prepareStatement("insert into t1(id) values (?)");   
   //1萬次循環  
   for(int i=1;i<=100000;i++){      
    pst.setInt(1, i);   
    pst.addBatch();   
    //每1000次提交一次  
    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) {   
   e.printStackTrace();   
  }   
}   
結果:
  • 1.使用statement 耗時142秒;
  • 2.使用PreparedStatement 耗時56秒;
  • 3.使用PreparedStatement + 批處理耗時:
    • a.50條插入一次,耗時5秒;
    • b.100條插入一次,耗時2秒;
    • c.1000條以上插入一次,耗時1秒;
  • 通過以上可以得出結論,在使用jdbc大批量插入數據時,明顯使用第三種方式(PreparedStatement + 批處理)性能更優。
結論:
方法一:普通方式處理大量數據的insert時,處理速度相當慢。  
*/  
PreparedStatement ps = null;  
//循環10000次  
for(int i = 0; i < 100000; i++) {  
    ps = conn.prepareStatement(sql);  
    ps.executeUpdate();  
}  
方法二:通過addBatch()的方式,將數據緩存在對象里面,通過最后執行executeBatch();方法提交,因此速度會快很多!  
*/  
PreparedStatement ps = con.prepareStatement(sql);  
for(int i = 0; i < 100000; i++) {  
    ps.setString(1, "1");  
    ps.setString(2, "2");  
    ps.addBatch();  
}  
ps.executeBatch();  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM