Java使用PreparedStatement和Statement实现批处理

批处理就是将一批一批SQL语句的处理,而不是一条一条语句进行处理。如当你有多条SQL语句要执行时,一次向服务器发送一条语句,这样虽然也可以达到效果,但是效率很差,而处理这个问题就可以使用批处理(即是一次向服务器发送多条SQL语句,然后让服务器一次性处理),批处理只针对更新语句(新增、删除、修改),所有批处理跟查询没有关系。

批处理:如通过多次调用PreparedStatement类的addBatch()方法把所有需要执行的SQL语句添加到“批”中,然后调用PreparedStatement的executeBatch()方法来执行当前“批”中的语句。

例:使用PreparedStatement对象进行批处理(向表中批量新增10000条数据)

   Connection conn=null;

   PreparedStatement ps=null;

   ResultSet rs =null;

   String sql ="INSERT INTO user VALUES(?,?,?)";

   @Test
   public void test() throws SQLException{

       try {
      conn= JDBCUtil.getConnection();
      ps = conn.prepareStatement(sql);
      for (int i = 0; i < 10000; i++) { 
             ps.setInt(1, i+1);
             ps.setString(2, "name"+i);
             ps.setString(3, "password"+i);
             ps.addBatch();

          }
       long start = System.currentTimeMillis();
       ps.executeBatch();
       long end = System.currentTimeMillis();
       long time ; //输出完成时间
       if(((end-start)/1000)==0){
          time =end-start;
          System.out.println(time+"毫秒");
       }else {
          time= (end-start)/1000 ;
          System.out.println(time+"秒");
       }

   } catch (SQLException e) {
      e.printStackTrace();
   }finally {
      JDBCUtil.close(rs, ps, conn);

   }

   }

运行上面代码,效果如下

发现完成批处理也需要9秒,其实是因为我使用的My SQL数据库,它默认批处理是关闭的,所以需要打开My SQL批处理,使用参数来打开rewriteBatchedStatements=true

修改完成后重新运行,控制台输出结果如下

使用Statement对象实现批处理

使用Statement对象虽然也可以实现批处理,但是这种方式效率太低,因为它所有的SQL语句都是没有预编译的,而通过PreparedStatement对象实现的批处理,addBatch()方法发送出去的都是预编译后的SQL语句,所以执行效率更高。(一般应用在SQL语句相同,参数不同的批处理),使用PreparedStatement对象实现的批处理比较常用于同一个表批量新增数据或更新数据。

Statement对象实现批处理代码

@Test

public void test1() {

   Statement st = null;

   Connection conn =null;

   try {
     conn= JDBCUtil.getConnection();
     st = conn.createStatement();
    for (int i = 0; i < 10000; i++) {
         int user_id=i+1;
         String username ="user"+i;
         String password ="password"+i;
         String sql ="INSERT INTO user VALUES('"+user_id+"','"+username+"','"+password+"')";
         st.addBatch(sql);
     }

      long start = System.currentTimeMillis();
      st.executeBatch();
      long end = System.currentTimeMillis();
      long time ;

      if(((end-start)/1000)==0){ //输出完成时间
           time =end-start;
           System.out.println(time+"毫秒");
      }else {
           time= (end-start)/1000 ;
           System.out.println(time+"秒");
         }
      } catch (SQLException e) {
          e.printStackTrace();
      }finally {
        try {
          st.close();
          conn.close();
      } catch (SQLException e) {
          e.printStackTrace();
      }

      }}

结果

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值