码迷,mamicode.com
首页 > 其他好文 > 详细

批量数据插入高效 转发

时间:2016-12-27 00:49:20      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:begin   system   cut   .com   auto   .exe   ati   执行   dstat   

  1. public static void insert() {  
  2.         // 开时时间  
  3.         Long begin = new Date().getTime();  
  4.         // sql前缀  
  5.         String prefix = "INSERT INTO tb_big_data (count, create_time, random) VALUES ";  
  6.         try {  
  7.             // 保存sql后缀  
  8.             StringBuffer suffix = new StringBuffer();  
  9.             // 设置事务为非自动提交  
  10.             conn.setAutoCommit(false);  
  11.             // Statement st = conn.createStatement();  
  12.             // 比起st,pst会更好些  
  13.             PreparedStatement pst = conn.prepareStatement("");  
  14.             // 外层循环,总提交事务次数  
  15.             for (int i = 1; i <= 100; i++) {  
  16.                 // 第次提交步长  
  17.                 for (int j = 1; j <= 10000; j++) {  
  18.                     // 构建sql后缀  
  19.                     suffix.append("(" + j * i + ", SYSDATE(), " + i * j  
  20.                             * Math.random() + "),");  
  21.                 }  
  22.                 // 构建完整sql  
  23.                 String sql = prefix + suffix.substring(0, suffix.length() - 1);  
  24.                 // 添加执行sql  
  25.                 pst.addBatch(sql);  
  26.                 // 执行操作  
  27.                 pst.executeBatch();  
  28.                 // 提交事务  
  29.                 conn.commit();  
  30.                 // 清空上一次添加的数据  
  31.                 suffix = new StringBuffer();  
  32.             }  
  33.             // 头等连接  
  34.             pst.close();  
  35.             conn.close();  
  36.         } catch (SQLException e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.         // 结束时间  
  40.         Long end = new Date().getTime();  
  41.         // 耗时  
  42.         System.out.println("cast : " + (end - begin) / 1000 + " ms");  
  43.     } 

批量数据插入高效 转发

标签:begin   system   cut   .com   auto   .exe   ati   执行   dstat   

原文地址:http://www.cnblogs.com/guolsblog/p/6224121.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!