zoukankan      html  css  js  c++  java
  • Java之批处理的实现

    批处理(batch)

    一、批处理介绍

      1、 批处理指的是一次操作中执行多条SQL语句

      2、 批处理相比于一次一次执行效率会提高很多

      3、 批处理主要是分两步:
          1.将要执行的SQL语句保存
          2.执行SQL语句
      4、 Statement和PreparedStatement都支持批处理操作,这里我们只需要掌握PreparedStatement的批处理方式:
          1) 方法:

            void addBatch()

              - 将要执行的SQL先保存起来,先不执行

              - 这个方法在设置完所有的占位符之后调用

            int[] executeBatch()

              - 这个方法用来执行SQL语句,这个方法会将批处理中所有SQL语句执行

          2) mysql默认批处理是关闭的,所以我们还需要去打开mysql的批处理:

            ? rewriteBatchedStatements=true

              我们需要将以上的参数添加到mysql的url地址中

          3)  注意:低版本的mysql-jdbc驱动也不支持批处理

    二、批处理的实现

      在连接数据库的url后面添加? rewriteBatchedStatements=true,开启批处理

     1   public void insertUser() throws SQLException {
     2         Connection conn = JDBCUtils.getConnection();
     3         PreparedStatement ps = null;
     4 
     5         String sql = "insert into t_user values(null,?)";
     6         ps = conn.prepareStatement(sql);
     7         for (int i = 0; i < 10000; i++) {
     8             ps.setString(1, "user" + i);
     9             ps.addBatch();  //将sql语句保存起来,先不执行
    10         }
    11         long start = System.currentTimeMillis();
    12         ps.executeBatch();  //执行批处理中所有的sql语句
    13         long end = System.currentTimeMillis();
    14         System.out.println("It costs" + (end - start) + "milliSeconds");
    15     }

      测试代码:

    1   @Test
    2     public void testBatch() throws Exception {
    3         Dao dao=new Dao();
    4         dao.insertUser();
    5     }

    测试结果:

      使用批处理只需要200多毫秒,而不开启批处理需要十几分钟,由此可见,使用批处理可以大大缩短sql语句执行时间

  • 相关阅读:
    bzoj4804
    bzoj2962
    bzoj4827
    bzoj2553
    bzoj3611
    BZOJ 1636: [Usaco2007 Jan]Balanced Lineup
    BZOJ 1635: [Usaco2007 Jan]Tallest Cow 最高的牛
    BZOJ 1634: [Usaco2007 Jan]Protecting the Flowers
    BZOJ 1631: [Usaco2007 Feb]Cow Party
    BZOJ 2582: [Usaco2012Jan]Bovine Alliance
  • 原文地址:https://www.cnblogs.com/java-zmj/p/8000605.html
Copyright © 2011-2022 走看看