mysql--存储过程

其类似于数据库中的函数,内部封装了SQL语句集合,会按照设计逻辑进行执行

1.创建存储过程:注意在存储时:需要先改变定界符--delimiter //可以进行修改;为//

delimiter //

create procedure p1()

begin

  语句集合

end //

delimiter ;

执行方法

call p1()

2.参数解析

其参数有三类in,out,inout

in:是传入参数

out:是传出参数,可以从中获取到结果集

inout:既是当传入又是可以当做返回值

含参实例

//创建存储过程
delimiter \\
create procedure p1(
        in i1 int,
        in i2 int,
        out i3,   
        inout i4 int   
)
begin
        declare d1 int;    ---声明变量
        declare d2 int defalut 0   ---设置默认值
        set d1 = 1;   ---赋值
        set i3  = d1 + d2
        set i4  = i4 +100
end\\
delimiter;

//执行存储过程
set @t1 = 4;
set @t2 = 0;
call p1(1,2,@t1,@t2)
select @t1,@t2;

含逻辑语句

delimiter //
drop procedure if exists p1()//
create procedure p1(
    in i1 int,
    out i2 int
)
begin
    declare tp int default 3;
    if i1 = 1 then
        set i2 = 100 + d2;
    elseif i1 = 2 then
        set i2 = 200 + d2;
    else then
        set i2 = 1000 + d2;
    end if;
end //
delimiter ;        

直接获取结果集

delimiter //
create proceduer p1()
begin
    select * from info;
end
delimiter ;

call p1() ---即可获取结果集

结果集与变量结合

delimiter //
drop procedure if exists p1(
    in i1 int,
    inout i2 int,
    out i3 int
)
begin
   declare d2 int default 3;
   select stu_id  into d2 from info where id = 5;
   select name from info where stu_id = d2;
end //
delimiter ;

 

python操作存储过程

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='t1')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 执行存储过程
#第二个是传入参数,多余的会自己去掉,out也是会跳过,只有in,和inout会在参数中获取数据
res = cursor.callproc('p1', args=(1, 22, 3, 4))
#若是存储过程中含有select结果集,或将结果集传入res中


# 获取执行完存储的参数
#命名规则@_存储过程名_获取参数序
#例如@_p1_0获取存储过程p1的第一个参数值
cursor.execute("select @_p1_0,@_p1_1,@_p1_2,@_p1_3")
result = cursor.fetchall()

conn.commit()
cursor.close()
conn.close()

 

删除存储过程:

drop procedure proc_name

 

调用存储过程:

#无参
call p1()

#有参
call p1(1,2)

#含有int,out,inout
set @p1=0;
set @p2=3;
call p1(1,2,@p1,@p2)

 

posted @ 2018-03-11 20:19  山上有风景  阅读(230)  评论(0编辑  收藏  举报