mysql -- 动态获取结果集(重点)

注意:语句传值的时候必须是带有@符号的参数,不能是自己的局部变量,一个@叫用户变量,两个@叫做全局变量。用户变量:当前用户的‘’全局变量‘’,用户状态存在时就存在,用户退出时消失。

初始版

delimiter \
drop procedure if exists p1()
create procedure p1()
begin
     declare i1 int;
     set i1 = 11;
     set @p1 = i1;
     
     prepare prod from 'select * from info where nid > ?';
     execute prod using @p1;    --执行预处理
     deallocate prepare prod;    --删除预处理
end \
delimiter ;

进阶版

delimiter \
drop procedure if exists p1()
create procedure p1(
    in strSQL varchar(128),            ----动态获取参数
    in nid int                                 ----动态获取参数
)
begin
     set @p1 = nid;
     set @sql1=strSQL;

     prepare prod from @sql1;
     execute prod using @p1;    --执行预处理
     deallocate prepare prod;    --删除预处理
end \
delimiter ;
    
#调用
call p1("select * from info where nid > ?",1)

python调用pymysql

row = cursor.callproc('p1',("select * from info where nid > ?",6));
res = cursor.fetchall()
原文地址:https://www.cnblogs.com/ssyfj/p/8546995.html