1.务必关掉自动提交
增强执行效率
- conn.setAutoCommit(false);
2.executeBatch失效问题
<1>务必将语句pstmt = conn.prepareStatement(sql);放到循环体外,否则只能插入一条语句
- <pre name="code" class="java"> int size = ipAdressList.size();
- try {
- conn = JdbcUtil.getConnection();
- conn.setAutoCommit(false);
- pstmt = conn.prepareStatement(sql);
- for (int i = 0; i < size; i++) {
- // pstmt = conn.prepareStatement(sql);只能插入最后一条
- ipAd = ipAdressList.get(i);
- int index = 1;
- pstmt.setObject(index++, ipAd.getadress());
- pstmt.setObject(index++, ipAd.getPort());
- pstmt.setObject(index++, ipAd.getSpeed());
- pstmt.setObject(index++, ipAd.getCountry());
- pstmt.setObject(index++, ipAd.getProvince());
- pstmt.setObject(index++, ipAd.getCity());
- pstmt.setObject(index++, ipAd.getIsp());
- pstmt.setObject(index++, ipAd.isDomestic());
- pstmt.setObject(index++, ipAd.isAlive());
- pstmt.addBatch();
- }
- pstmt.executeBatch();
- conn.commit();
- } catch (Exception e) {
- e.printStackTrace();
- }finally {
- JdbcUtil.close(rs, stmt, pstmt, conn);
- }</pre><br><br>
<2>务必最后提交
- conn.commit();