存储过程

一、无参存储过程

delimiter //
create procedure p1() 
BEGIN
    select * from db7.teacher;  # 写sql语句
END //
delimiter ;

# MySQL中调用
call p1();

#Python中调用
cursor.callproc('p1')  # 执行sql语句
print(cursor.fetchall()) # 打印结果

二、有参存储过程

delimiter //
create procedure p2(in n1 int,in n2 int,out res int)
BEGIN
    select * from db7.teacher where tid >n1 and tid < n2;
    set res = 1;
END //
delimiter ;


# MySQL中调用
set @x=0
call p2(2,4,@x);
select @x;  # 查看返回值

# Python中调用
cursor.callproc('p2',(2,4,0)) #参数代表 @_p2_0=2,@_p2_1=4,@_p2_2=0
print(cursor.fetchall()) # 查看结果
cursor.execute(select @_p2_2) #取返回值
print(cursor.fetchone()) #查看返回值