存储过程

存储过程是一个SQL语句集合,当主动去调用存储过程是,可以进行复杂的逻辑。

创建存储过程:
(delimiter用来切换SQL语句的终止符)
delimiter //
create procedure p1()
BEGIN
select * from t1;
END //
delimiter ;

执行存储过程
MYSQL客户端:
无参数
call proc_name()

有参数in
call porc_name(1,2)

有参数in,out,inout
set @t1 = 0;
set @t2 = 3;
call proc_name(1,2,@t1,@t2) # in in out inout
select @t1, @t2

pymysql:
无参数
callproc('proc_name')
有参数
callproc('proc_name', args(1,22,3,4)) # in in out inout
execute('select @_proc_name_0, @_proc_name_1, @_proc_name_2, @_proc_name_3') # 1 22 3没有意义 4

存储过程可以接受参数:
in 仅用于传入参数
out 仅用于返回值,传入的是值的引用,内部使用时默认为null
inout 既可以传入又可以当作返回值
示例:delimiter //
create procedure p1(
in arg1 int,
out arg2 varchar(50),
inout arg3 int
)
BEGIN
arg2 = 123;
arg3 = arg3 + 111;
...
无法返回值
END //
delimiter ;

@i2 = 666
call p1(1,@i1,@i2) #@i1=null,@i2=666 ==> @i1=123,@i2=777

存储过程内部变量
声明时必须使用DECLARE
declare v int;
declare c int default 0;

修改时必须加关键字SET
set v = 1;

删除存储过程
drop procedure proc_name()

条件语句:
if 条件 then
语句;
elseif 条件 then
语句;
else
语句;
end if;

循环语句:
while循环
while 条件 do
语句;
end while;

repeat循环
repeat
语句;
until 条件;
end repeat;

loop循环
loop_label: loop
语句
if 条件 then
leave loop_label;
end if;
end loop;

动态执行SQL语句
declare p1 int;
set @p1 = 11; # 必须用@开头的定义

PREPARE prod FROM 'select * from tb2 where nid > ?' # 创建一个sql语句
EXECUTE prod USING @p1; # 格式化字符串
DEALLOCATE PREPARE prod; # 执行
  
  利用存储过程来防止sql语句注入
     cursor.callproc('存储过程名', 参数(sql语句等))

posted on 2018-09-23 11:18  风度翩翩的机器空  阅读(182)  评论(0编辑  收藏  举报

导航