113 저장 프로 시저

저장 프로시 저는 일련의 실행 가능한 SQL 문을 포함하고 저장 프로시 저는 MySQL에 저장되며 이름을 호출하여 내부에있는 SQL을 실행할 수 있습니다.

저장 프로 시저 사용의 장점 :

# 1. 프로그램과 SQL의 분리를 실현하기 위해 프로그램이 작성한 SQL 문을 대체하는 데 사용됩니다.

# 2. 네트워크 전송을 기준으로 별칭으로 전송되는 데이터 양은 적고 SQL로 직접 전송되는 데이터 양은 많음

저장 프로 시저 사용의 단점 :

# 1. 프로그래머가 기능을 확장하는 것은 편리하지 않습니다.

程序与数据库结合使用的三种方式


#方式一:
    MySQL:存储过程
    程序:调用存储过程

#方式二:
    MySQL:
    程序:纯SQL语句

#方式三:
    MySQL:
    程序:类和对象,即ORM(本质还是纯SQL语句)


# 创建无参存储过程
delimiter $$
create procedure p1()
begin
    select * from emp;
end $$

delimiter ;

call p1();

# 创建有参存储过程
delimiter $$
create procedure p2(
    in n int,
    out res int
)
begin
    select * from emp where id > n;
    set res=1;
end $$

delimiter ;



==========================>在mysql里如何调用存储过程
mysql> set @x=1111;
Query OK, 0 rows affected (0.00 sec)

mysql> call p2(3,x);
ERROR 1414 (42000): OUT or INOUT argument 2 for routine db4.p2 is not a variable or NEW pseudo-variable in BEFORE trigger
mysql> call p2(3,@x);
+----+------------+--------+------+--------+
| id | name       | sex    | age  | dep_id |
+----+------------+--------+------+--------+
|  4 | yuanhao    | female |   28 |    202 |
|  5 | liwenzhou  | male   |   18 |    200 |
|  6 | jingliyang | female |   18 |    204 |
|  7 | lili       | female |   48 |   NULL |
+----+------------+--------+------+--------+
4 rows in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

mysql> select @x;
+------+
| @x   |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

mysql>
==========================>在pymysql里如何调用存储过程

Python 구현 :

import pymysql  # pip3 install pymysql

conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="123", db="db4", charset="utf8mb4")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)


cursor.callproc('p2',(3,0))  # @_p2_0=3,@_p2_1=0
'''
set @_p2_0=3
set @_p2_1=0

call p2(@_p2_0,@_p2_1);

'''

print(cursor.fetchall())

cursor.execute("select @_p2_1;")
print(cursor.fetchall())

cursor.execute("select @_p2_0;")
print(cursor.fetchall())

cursor.close()
conn.close()

추천

출처blog.csdn.net/qq_40808228/article/details/108502373