你的位置:首页 > Java教程

[Java教程]【实践】jdbc批量插入数据


参考文献:http://my.oschina.net/u/1452675/blog/203670

http://superjavason.iteye.com/blog/255423

 1 /*测试批量写入数据*/ 2     long start = System.currentTimeMillis(); 3     DaoRecord daoRecord = new DaoRecord(); 4     List<T> list = new ArrayList<T>(); 5     for(int i = 1; i <= 1000; i++){ 6       for(int j = 1; j <= 1000; j++){ 7         T t = new T(); 8         t.setI(i); 9         t.setJ(j);10         list.add(t);11       }12     }13     daoRecord.InsertBatch(list);14     System.out.println("耗时:" + (System.currentTimeMillis()-start)+"毫秒");

 

 1 //批量写入数据测试 2   public void InsertBatch(List<T> list){ 3     String sql = "insert into t(go,back) values(?,?)"; 4     DBHelper dbh = new DBHelper(sql); 5     Connection conn = dbh.returnConn(); 6     try { 7       conn.setAutoCommit(false);//注意此句一定要为false,原因见第一篇参考文献 8       PreparedStatement ps = conn.prepareStatement(sql); 9       for(int i = 0; i < list.size(); i++){10         ps.setInt(1, list.get(i).getI());11         ps.setInt(2, list.get(i).getJ());12         ps.addBatch();13         if (i % 10000 == 0){14            ps.executeBatch();15            conn.commit();16          }17       }18       ps.executeBatch();19       conn.commit();20       conn.close();21     } catch (SQLException e) {22       // TODO 自动生成的 catch 块23       e.printStackTrace();24     }25   }

数据表:

  

实验结果: