MySql存储过程

---恢复内容开始---

存储过程:

建立存储过程

create procedure 过程名(in  参数1 数据类型,out 参数2 数据类型):

begin

  代码块

end

同样需要使用delimiter 修改结束符,sql使用call 过程名(参数1) 来调用,pymysql使用cursor.callproc('过程名‘,(参数1,))来调用

----in:传入的参数

---out:传出的参数

create procedure 过程名(in  参数1 数据类型,out 参数2 数据类型):

begin

  代码块
      参数2 = 返回值
    
    
end;
---参数2 为 @变量名,

 mysql调用

set@变量名 =  任意值 (@变量名为session级别变量);

call 过程名(参数1,@变量名);#得到结果集

select @变量名; #得到out的参数

pymysql调用

cursor.callporc('过程名‘,(参数1,参数2))#如果参数为out型,则可以出入符合类型的任意值

r1 = cursor.fetchall()#获得结果集

cursor.execute('select @_过程名_参数位置’)#参数位置为调用时参数元组的索引,从0 开始

r2 =cursor.defchall()#获得相关参数

事物

创建事物

create procedure 事物名(out 参数名 数据类型)

begin

  declare exit handler fro sqlexception

  begin

  --error

    set 参数名 = 1;

    rollback;

  end;

  start transaction;

    代码块;

  commit;

  --sucess

   set 参数名 = 2 ;

   end;

 包含循环、游标的创建过程

create procedure 过程名()

begin

  declare 变量1 数据类型;

  declare 变量2 数据类型; 

  declare done int default faulse;--声明变量done默认为faulse

  declare 游标名 cursor for select 字段名1,字段名2 from 表名;

  declare continue handler for not found set done = True;--检测数据,如果没有数据则设置done 为true

  open 游标名;

    循环名:loop

        fetch 游标名 into 变量1,变量2;

        if done then leave 循环名;

      end if;

      代码块

      insert into   表名(字段名)values(变量名);

    end loop 循环名;

  close 游标名;

end;

动态执行sql(防止注入)

create procedure 过程名(

  in 变量名  int)

begin 

  set @临时变量名 = 变量名;

  prepare  语句名 from ‘select *from student where sid>?';

  execute 语句名 using @临时变量名;

  deallocate prepare 语句名;

end;

原文地址:https://www.cnblogs.com/modengdai/p/9912531.html