1. 程式人生 > >mysql之存儲過程

mysql之存儲過程

參數 begin etc style 基於 語句 code 接收參數 where

存儲過程包含了一系列可執行的sql語句,存儲過程存放於MySQL中,通過調用它的名字可以執行其內部的一堆sql

存儲過程的優點

#1. 用於替代程序寫的SQL語句,實現程序與sql解耦

#2. 基於網絡傳輸,傳別名的數據量小,而直接傳sql數據量大

無參的存儲過程

delimiter //
create procedure p1()
BEGIN
    select * from blog;
    INSERT into blog(name,sub_time) values("xxx",now());
END //
delimiter ;

#在mysql中調用
call p1() 

#在python中基於pymysql調用
cursor.callproc(p1) print(cursor.fetchall())

有參的存儲過程

對於存儲過程,可以接收參數,其參數有三類:

#in          僅用於傳入參數用
#out        僅用於返回值用
#inout     既可以傳入又可以當作返回值

帶in的存儲過程

mysql> select * from emp;
+----+----------+-----+--------+
| id | name     | age | dep_id |
+----+----------+-----+--------+
|  1 | zhangsan |  18 |      1 |
|  2 | lisi     |  19 |      1 |
|  3 | egon     |  20 |      2 |
|  5 | alex     |  18 |      2 |
+----+----------+-----+--------+
4 rows in
set (0.30 sec) mysql> delimiter // mysql> create procedure p2(in n1 int, in n2 int) -> begin -> select * from emp where id >n1 and id <n2; -> end // Query OK, 0 rows affected (0.28 sec) mysql> delimiter ; mysql> call p2(1,3) -> ; +----+------+-----+--------+ | id | name | age | dep_id | +----+------+-----+--------+ | 2 | lisi | 19 | 1 | +----+------+-----+--------+ 1 row in
set (0.07 sec) Query OK, 0 rows affected (0.07 sec)
#在python中基於pymysql調用
cursor.callproc(p2,(1,3))
print(cursor.fetchall())

mysql之存儲過程