时间:2021-07-01 10:21:17 帮助过:4人阅读
DELIMITER \\
CREATE FUNCTION f1(
i1 INT,
i2 INT)
RETURNS INT
BEGIN
DECLARE num INT DEFAULT 0;
SET num = i1 + i2;
RETURN(num);
END \\
DELIMITER ;
存储过程:
保存在MySQL上的一个别名 => 一坨SQL语句 precedure() 用于替代程序员写SQL语句
用参数之前要声明declare - - 麻烦
方式一:
MySQL: 存储过程
程序:调用存储过程
方式二:
MySQL:。。
程序:SQL语句
方式三:
MySQL:。。
程序:类和对象(SQL语句)
1 简单
delimiter //
create procedure p1()
begin
select * from user ;
insert into teacher(tname) value (‘kk‘);
end //
delimiter ;
call p1();
2 传参数(in,out ,inout)
delimiter //
create procedure p2(
in n1 int ,
in n2 int
)
begin
select * from student where sid >n1;
end //
delimiter ;
call p2(12,2)
cursor.callproc(‘p2‘,(12,2))
3 参数 out(用于一个可以返回的结果)
DELIMITER //
CREATE PROCEDURE p4 (
IN n1 INT,
OUT n2 VARCHAR(20)
)
BEGIN
SET n2 = ‘执行成功‘;
SELECT * FROM USER WHERE nid > n2;
INSERT INTO quanxian(POWER) VALUE (‘choudidi‘);
END //
DELIMITER ;
set @v1 = 10;
call p2(12,@v1)
select @v1;
pymysql:
cursor.callproc(‘p4‘,(2,3))
result = cursor.fetchall()
print(result)
4 游标:用与循环
DELIMITER //
CREATE PROCEDURE p6()
BEGIN
#声明循环参数
DECLARE row_id INT;
DECLARE row_num INT;
DECLARE done INT DEFAULT FALSE;
DECLARE temp INT;
#声明游标 游标done
DECLARE my_cursor CURSOR FOR SELECT id ,num FROM A;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN my_cursor;
xx:LOOP (循环)
FETCH my_cursor INTO row_id , row_num;
IF done THEN
LEAVE xx;
END IF;
SET temp = row_id + row_num;
INSERT INTO B(number) VALUE (temp);
END LOOP xx;
CLOSE my_cursor;
END //
DELIMITER ;
5 动态执行SQL (防止sql注入)
DELIMITER //
CREATE PROCEDURE p7(
IN tpl VARCHAR(244),
IN ARG INT
)
BEGIN
#预编译
#sql = 格式化 tpl+arg
#执行
SET @xo = ARG;
PREPARE xxx FROM ‘select * from student where sid > ?‘;
EXECUTE xxx USING @xo;
DEALLOCATE PREPARE prod;
END //
DELIMITER ;
CALL p7(‘select * from tb where id> ?‘,9)
Mysql学习日记-05视图,触发器,函数,存储过程
标签:smi row das exec roc handle iter from where