存储过程将存入的一系列sql语句进行预编译,执行并存放在数据库中,之后如果需要使用sql语句对这一组sql进行访问时可以直接提取(
一、存储过程(stored procedure)
存储过程将存入的一系列sql语句进行预编译,执行并存放在数据库中,之后如果需要使用sql语句对这一组sql进行访问时可以直接提取(很好理解 存储过程就是将sql执行过程存储在数据库中,来方便提取)。
优点:1.多次提取,减少编译时间,2.因为每次提取都需要传入sql语句,如果用存储过程名来调用的话,,就减少了访问流量3.增加了重用(可以相较之与(函数对编程的影响))
缺点:1.存储过程将会占用内存空间,并且复杂的过程操作需要一定的cpu 2.存储过程难以调试,如果存储过程太过复杂,不有利于业务逻辑3.存储过程高级,难以维护。
delimiter $$ // 设置注释
create procedure countorderbystatus(
in orderstatus varchar(25), //需要给定存入使用的参数
out total int) //需要给定输出的参数
begin
select count(ordernumber)
into total
from orders
where status = orderstatus;
end$$
delimiter ;
这个存储过程接受两个过程参数 一个是输入参数orderstatus,另一个是输出参数 total 最后可以使用call countorderbystatus('23',@title)来进行调用,变量前面要加@.
参数类型
in 参数名 参数类型 :表示该参数需要在创建存储类型时给出,以便在下面的语句中使用
官方样例:
delimiter //
create procedure getofficebycountry(in countryname varchar(255))
begin
select *
from offices
where country = countryname;
end //
delimiter ;
call getofficebycountry('usa')//调用
out 参数名 参数类型:该参数在执行完所有的参数语句后可以返回.
inout 参数名 参数类型: 该参数的不同之处在于它传入的参数需要赋值,并且在callprogram之后他的参数值将会被修改返回给变量值.
delimiter $$
create procedure set_counter(inout count int(4),in inc int(4))//传入一个inout参数和一个in参数
begin
set count = count + inc;
end$$
delimiter ;
现在尝试调用此储存过程
set @counter = 1;
call set_counter(@counter,1); -- 2
call set_counter(@counter,1); -- 3 //@count的值已经被修改
call set_counter(@counter,5); -- 8
select @counter; -- 8
谓词逻辑:
if(基本)
if if_expression then commands
[elseif elseif_expression then commands]
[else commands]
end if;
while loop
while expression do
statements
end while
repeat
statements;
until expression
end repeat
case
case case_expression
when when_expression_1 then commands
when when_expression_2 then commands
...
else commands
end case;
注意事项:能用case用case,能简化就简化
重点
如何python调用 callproc 进行调用储存过程
1.创建完整的mysql数据库连接
2.使用cursor()初始化数据库游标
3.使用游标来调用callproc函数 里面添加 需要传入的变量 例如 callproc(name,args),args=['21',syh];
3.cursor可以传递出一系列的结果集,使用storeresult来获取一系列的iterator指向结果集
4.用fetchall方法获取结果
callproc 无法直接获得out和inout变量 ,但是变量存在server中,可以通过@_procname_n 来获取变量值,可以按照传入参数的位置获取,如第1个 select @_procname_0
from mysql.connector import mysqlconnection, error
from python_mysql_dbconfig import read_db_config
def call_find_all_sp():
try:
db_config = read_db_config()
conn = mysqlconnection(**db_config)
cursor = conn.cursor()
cursor.callproc('find_all')
# print out the result
for result in cursor.stored_results():
print(result.fetchall())
except error as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
call_find_all_sp()
本文永久更新链接地址:
