执行Batch批处理遇到的问题

1.务必关掉自动提交

增强执行效率

  1. conn.setAutoCommit(false);  


2.executeBatch失效问题

<1>务必将语句pstmt = conn.prepareStatement(sql);放到循环体外,否则只能插入一条语句

  1. <pre name="code" class="java">      int size = ipAdressList.size();  
  2.         try {  
  3.             conn = JdbcUtil.getConnection();  
  4.             conn.setAutoCommit(false);  
  5.             pstmt = conn.prepareStatement(sql);  
  6.             for (int i = 0; i < size; i++) {  
  7.             //  pstmt = conn.prepareStatement(sql);只能插入最后一条  
  8.                 ipAd = ipAdressList.get(i);  
  9.                 int index = 1;  
  10.                 pstmt.setObject(index++, ipAd.getadress());  
  11.                 pstmt.setObject(index++, ipAd.getPort());  
  12.                 pstmt.setObject(index++, ipAd.getSpeed());  
  13.                 pstmt.setObject(index++, ipAd.getCountry());  
  14.                 pstmt.setObject(index++, ipAd.getProvince());  
  15.                 pstmt.setObject(index++, ipAd.getCity());  
  16.                 pstmt.setObject(index++, ipAd.getIsp());  
  17.                 pstmt.setObject(index++, ipAd.isDomestic());  
  18.                 pstmt.setObject(index++, ipAd.isAlive());  
  19.                 pstmt.addBatch();  
  20.             }  
  21.             pstmt.executeBatch();  
  22.             conn.commit();  
  23.         } catch (Exception e) {  
  24.             e.printStackTrace();  
  25.         }finally {  
  26.             JdbcUtil.close(rs, stmt, pstmt, conn);  
  27.         }</pre><br><br>  

 


<2>务必最后提交

    1. conn.commit(); 
posted @ 2017-08-31 16:04  人情世故  阅读(452)  评论(0编辑  收藏  举报
"不管做什么,只要坚持下去就会看到不一样!在路上,不卑不亢!"