JavaWeb学习笔记(十五)—— 使用JDBC进行批处理

一、什么是批处理

  批处理就是一批一批的处理,而不是一个一个的处理!

  当你有10条SQL语句要执行时,一次向服务器发送一条SQL语句,这么做效率上很差!处理的方案是使用批处理,即一次向服务器发送多条SQL语句,然后由服务器一次性处理。

  批处理只针对更新(增、删、改)语句,批处理没有查询什么事儿!

  JDBC实现批处理有两种方式:statement和preparedstatement

二、Statement批处理

  可以多次调用Statement类的addBatch(String sql)方法,把需要执行的所有SQL语句添加到一个“批”中,然后调用Statement类的executeBatch()方法来执行当前“批”中的语句。

  • void addBatch(String sql):添加一条语句到“批”中;
  • int[] executeBatch():执行“批”中所有语句。返回值表示每条语句所影响的行数据;
  • void clearBatch():清空“批”中的所有语句。

2.1 使用Statement完成批处理范例

【编写测试的SQL脚本创建表】

 create table testbatch
(
     id int primary key,
     name varchar(20)
);

【编写测试代码】

/**
 * 使用Statement实现JDBC批处理操作
 */
public class JdbcBatchHandleByStatement {
    @Test
    public void testJdbcBatchHandleByStatement() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql1 = "insert into testbatch(id,name) values(1,'aaa')";
            String sql2 = "insert into testbatch(id,name) values(2,'bbb')";
            String sql3 = "insert into testbatch(id,name) values(3,'CCC')";
            String sql4 = "insert into testbatch(id,name) values(4,'DDD')";
            String sql5 = "update testbatch set name='zhangsan' where id=1";
            String sql6 = "insert into testbatch(id,name) values(5,'lisi')";
            String sql7 = "delete from testbatch where id=2";
            st = conn.createStatement();
            //添加要批量执行的SQL
            // st内部有个集合,用来装载sql语句
            st.addBatch(sql1);
            st.addBatch(sql2);
            st.addBatch(sql3);
            st.addBatch(sql4);
            st.addBatch(sql5);
            st.addBatch(sql6);
            st.addBatch(sql7);
            //执行批处理SQL语句,即一次把批中的所有sql语句发送给服务器
            st.executeBatch();
            //清除批处理命令
            st.clearBatch();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn, st,rs);
        }
    }
}

  当执行了“批”之后,“批”中的SQL语句就会被清空!也就是说,连续两次调用executeBatch()相当于调用一次!因为第二次调用时,“批”中已经没有SQL语句了。

  还可以在执行“批”之前,调用Statement的clearBatch()方法来清空“批”!

2.2 采用Statement.addBatch(sql)方式实现批处理的优缺点

  优点:可以向数据库发送多条不同的SQL语句。
  缺点:SQL语句没有预编译。当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句。例如:

Insert into user(name,password) values('aa','111');
Insert into user(name,password) values('bb','222');
Insert into user(name,password) values('cc','333');
Insert into user(name,password) values('dd','444');

三、PreparedStatement批处理

  PreparedStatement的批处理有所不同,因为每个PreparedStatement对象都绑定一条SQL模板。所以向PreparedStatement中添加的不是SQL语句,而是给“?”赋值。

3.1 使用PreparedStatement完成批处理范例

/**
 * 使用prepareStatement实现JDBC批处理操作
 * pstmt对象内部有集合
 * 1.用循环疯狂向pstmt中添加sql参数,它自己有模板,使用一组参数与模板就可以匹配出一条sql语句
 * 2.调用它的执行批方法,完成向数据库发送
 */
public class JdbcBatchHandleByPrepareStatement {
    @Test
    public void testJdbcBatchHandleByPrepareStatement() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "insert into testbatch(id,name) values(?,?)";
            pstmt = conn.prepareStatement(sql);

            // 疯狂的添加参数
            for (int i = 0; i < 10000; i++) {
                pstmt.setInt(1, i + 1);
                pstmt.setString(2, "stu_" + i);

                // 添加批,这一组参数就保存到集合中了
                pstmt.addBatch();
            }
            long start = System.currentTimeMillis();
            // 执行批
            pstmt.executeBatch();
            long end = System.currentTimeMillis();

            System.out.println(end - start);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn, pstmt, rs);
        }
    }
}

3.2 采用PreparedStatement.addBatch()方式实现批处理的优缺点

  优点:发送的是预编译后的SQL语句,执行效率高。
  缺点:只能应用在SQL语句相同,但参数不同的批处理中。因此此种形式的批处理经常用于在同一个表中批量插入数据,或批量更新表的数据。

  注意:MySQL的批处理需要通过参数来打开:rewriteBatchedStatements=true

  

猜你喜欢

转载自www.cnblogs.com/yft-javaNotes/p/10505556.html