zoukankan      html  css  js  c++  java
  • 不好的MySQL过程编写习惯

        刚才为了测试一个东西,写了个存储过程:  

        

    delimiter $$
    
    drop procedure if exists sp_test$$
    
    create procedure sp_test()
    begin
      declare v_cnt int;
      set v_cnt = 0;
      while v_cnt < 100000
      do
        insert into t1 select v_cnt, v_cnt+1, v_cnt+2, v_cnt+3;
        set v_cnt = v_cnt + 1;
      end while; 
    end $$
    
    delimiter ;

         很简单的一个过程,想要给表里插入10万条数据而已,但是实际执行过程中发现耗时很长,五分钟过去了还是没有执行完毕,于是我就把过程停掉了。又看了一遍过程我发现自己犯了一个曾经反复和别人强调过的错误,这种插入数据的过程,一定不要在循环中提交事务。MySQL默认是自动提交事务的,这一点众所周知,于是我的过程里每一条插入结束后都会自动将数据提交,于是每次提交都会写一次redo,于是我这个要写10万次redo,这个开销实在是很大很大的,于是我将过程做了简单的修改:

         

    delimiter $$
    
    drop procedure if exists sp_test$$
    
    create procedure sp_test()
    begin
      declare v_cnt int;
      set v_cnt = 0;
      start transaction;
      while v_cnt < 100000
      do
        insert into t1 select v_cnt, v_cnt+1, v_cnt+2, v_cnt+3;
        set v_cnt = v_cnt + 1;
      end while; 
      commit;
    end $$
    
    delimiter ;

         

         效果非常好。顺便说一句,头一次写的那个过程还有一个问题,比如说我刚才不耐烦的将terminal关掉了,但是我根本不知道我关掉的时候过程执行到哪里去了,比如我们有时候执行的时候发生了什么不可预知的错误,那么我们也就不知道现在执行到什么位置了。因此不要在循环中自动提交事务,要显式的开启事务。

  • 相关阅读:
    SpringMVC将表单对象序列化成Json字符串提交,以List接收
    Spring boot下添加filter
    如何将查出的日期Data类型以Json格式输出到前端
    ajax传递给后台数组参数方式
    Spring boot + Gradle + Eclipse打war包发布总结
    Spring-data-jpa详解
    SpringMVC配置过程中出现的问题!
    spring 集成shiro 之 自定义过滤器
    完全跨域的单点登录
    Java8 Lambda表达式
  • 原文地址:https://www.cnblogs.com/wingsless/p/5041838.html
Copyright © 2011-2022 走看看