批量插入数据优化

  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.     } 

猜你喜欢

转载自blog.csdn.net/qq_38743952/article/details/78273893