1. 程式人生 > >Mysql內建功能《四》儲存過程

Mysql內建功能《四》儲存過程

儲存過程

一 儲存過程介紹

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

使用儲存過程的優點:

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

#2. 基於網路傳輸,傳別名的資料量小,而直接傳sql資料量大

使用儲存過程的缺點:

#1. 程式設計師擴充套件功能不方便

補充:程式與資料庫結合使用的三種方式

#方式一:
    MySQL:儲存過程
    程式:呼叫儲存過程

#方式二:
    MySQL:
    程式:純SQL語句

#方式三:
    MySQL:
    程式:類和物件,即ORM(本質還是純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     既可以傳入又可以當作返回值
delimiter //
create procedure p2(
    in n1 int,
    in n2 int
)
BEGIN

    select * from blog where id > n1;
END //
delimiter ;

#在mysql中呼叫
call p2(3,2)

#在python中基於pymysql呼叫
cursor.callproc('p2',(3,2))
print(cursor.fetchall())

in:傳入引數
delimiter //
create procedure p3(
    in n1 int,
    out res int
)
BEGIN
    select * from blog where id > n1;
    set res = 1;
END //
delimiter ;

#在mysql中呼叫
set @res=0; #0代表假(執行失敗),1代表真(執行成功)
call p3(3,@res);
select @res;

#在python中基於pymysql呼叫
cursor.callproc('p3',(3,0)) #0相當於set @res=0
print(cursor.fetchall()) #查詢select的查詢結果

cursor.execute('select @_p3_0,@_p3_1;') #@p3_0代表第一個引數,@p3_1代表第二個引數,即返回值
print(cursor.fetchall())

out:返回值
delimiter //
create procedure p4(
    inout n1 int
)
BEGIN
    select * from blog where id > n1;
    set n1 = 1;
END //
delimiter ;

#在mysql中呼叫
set @x=3;
call p4(@x);
select @x;


#在python中基於pymysql呼叫
cursor.callproc('p4',(3,))
print(cursor.fetchall()) #查詢select的查詢結果

cursor.execute('select @_p4_0;') 
print(cursor.fetchall())

inout:既可以傳入又可以返回

四 執行儲存過程

-- 無引數
call proc_name()

-- 有引數,全in
call proc_name(1,2)

-- 有引數,有in,out,inout
set @t1=0;
set @t2=3;
call proc_name(1,2,@t1,@t2)

執行儲存過程

在MySQL中執行儲存過程-- 無引數
call proc_name()

-- 有引數,全in
call proc_name(1,2)

-- 有引數,有in,out,inout
set @t1=0;
set @t2=3;
call proc_name(1,2,@t1,@t2)

執行儲存過程

在MySQL中執行儲存過程
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 執行儲存過程
cursor.callproc('p1', args=(1, 22, 3, 4))
# 獲取執行完儲存的引數
cursor.execute("select @_p1_0,@_p1_1,@_p1_2,@_p1_3")
result = cursor.fetchall()

conn.commit()
cursor.close()
conn.close()


print(result)

在python中基於pymysql執行儲存過程

五 刪除儲存過程

drop procedure proc_name;