JDBC学习(六)批处理

批处理就是一批一批的处理,只针对更新(增,删,改)语句,不包括查询。

对于mysql 默认是关闭批处理的,需要在连接url中添加参数

rewriteBatchedStatements=true

Statement批处理

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

  • void addBatch(String sql):添加一条语句到“批”中;
  • int[] executeBatch():执行“批”中所有语句。返回值表示每条语句所影响的行数据;
  • void clearBatch():清空“批”中的所有语句。
for(int i = 0; i < 10; i++) {
				String number = "S_10" + i;
				String name = "stu" + i;
				int age = 20 + i;
				String gender = i % 2 == 0 ? "male" : "female";
				String sql = "insert into stu values('" + number + "', '" + name + "', " + age + ", '" + gender + "')";
				stmt.addBatch(sql);
			}
			stmt.executeBatch();

PreparedStatement批处理

preparedStatement批处理更加方便,通过添加一个sql 模板,可以多轮向其中添加参数。每轮参数添加完了,调用addBatch()方法

最后执行executeBatch()

@Test
    public void fun1() throws Exception {

        //获取mysql 服务器的连接

        Connection cn= jdbcUtils.getConnection();

        String sql="insert into student(username,`number`) values(?,?)";
        PreparedStatement ps=cn.prepareStatement(sql);


        for(int i=0;i<1000;i++){
            ps.setString(1,"stu_"+i);
            ps.setString(2,"00"+i);

            ps.addBatch();
        }

        long start=System.currentTimeMillis();
        //执行
        ps.executeBatch();
        long end=System.currentTimeMillis();
        System.out.println(end-start);
    }

运行结果

68822(没有开启批处理)

232(开启批处理)

猜你喜欢

转载自blog.csdn.net/SICAUliuy/article/details/88791856