溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在mysql中使用存儲(chǔ)過程

發(fā)布時(shí)間:2021-03-22 17:31:19 來源:億速云 閱讀:159 作者:Leah 欄目:MySQL數(shù)據(jù)庫

如何在mysql中使用存儲(chǔ)過程?相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

存儲(chǔ)過程包含了一系列可執(zhí)行的sql語句,存儲(chǔ)過程存放于MySQL中,通過調(diào)用它的名字可以執(zhí)行其內(nèi)部的一堆sql

存儲(chǔ)過程的優(yōu)點(diǎn)

#1. 用于替代程序?qū)懙腟QL語句,實(shí)現(xiàn)程序與sql解耦

#2. 可以通過直接修改存儲(chǔ)過程的方式修改業(yè)務(wù)邏輯(或bug),而不用重啟服務(wù)器

#3. 執(zhí)行速度快,存儲(chǔ)過程經(jīng)過編譯之后會(huì)比單獨(dú)一條一條執(zhí)行要快

#4. 減少網(wǎng)絡(luò)傳輸,尤其是在高并發(fā)情況下這點(diǎn)優(yōu)勢大,存儲(chǔ)過程直接就在數(shù)據(jù)庫服務(wù)器上跑,所有的數(shù)據(jù)訪問都在服務(wù)器內(nèi)部進(jìn)行,不需要傳輸數(shù)據(jù)到其它終端。

存儲(chǔ)過程的缺點(diǎn)

1.SQL本身是一種結(jié)構(gòu)化查詢語言,加上了一些控制(賦值、循環(huán)和異常處理等),但不是OO的,本質(zhì)上還是過程化的,面對復(fù)雜的業(yè)務(wù)邏輯,過程化的處理會(huì)很吃力。這一點(diǎn)算致命傷,即只能應(yīng)用在邏輯簡單的業(yè)務(wù)上。

2.不便于調(diào)試?;旧蠜]有較好的調(diào)試器,很多時(shí)候是用print來調(diào)試,但用這種方法調(diào)試長達(dá)數(shù)百行的存儲(chǔ)過程簡直是噩夢。好吧,這一點(diǎn)不算啥,C#/java一樣能寫出噩夢般的代碼。

3.沒辦法應(yīng)用緩存。雖然有全局臨時(shí)表之類的方法可以做緩存,但同樣加重了數(shù)據(jù)庫的負(fù)擔(dān)。如果緩存并發(fā)嚴(yán)重,經(jīng)常要加鎖,那效率實(shí)在堪憂。

4.無法適應(yīng)數(shù)據(jù)庫的切割(水平或垂直切割)。數(shù)據(jù)庫切割之后,存儲(chǔ)過程并不清楚數(shù)據(jù)存儲(chǔ)在哪個(gè)數(shù)據(jù)庫中。

無參的存儲(chǔ)過程

delimiter //
create procedure p1()
BEGIN
  select * from blog;
  INSERT into blog(name,sub_time) values("xxx",now());
END //
delimiter ;
#在mysql中調(diào)用
call p1()
#在python中基于pymysql調(diào)用
cursor.callproc('p1')
print(cursor.fetchall())

有參的存儲(chǔ)過程

對于存儲(chǔ)過程,可以接收參數(shù),其參數(shù)有三類:

#in          僅用于傳入?yún)?shù)用
#out        僅用于返回值用
#inout     既可以傳入又可以當(dāng)作返回值

帶in的存儲(chǔ)過程

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調(diào)用
cursor.callproc('p2',(1,3))
print(cursor.fetchall())

帶有out

mysql> delimiter //
mysql> create procedure p3( in n1 int, out res int)
  -> begin
  ->  select * from emp where id >n1;
  ->  set res=1;
  -> end //
Query OK, 0 rows affected (0.28 sec)
mysql> delimiter ;
mysql> set @res=0;
Query OK, 0 rows affected (0.00 sec)
mysql> call p3(3,@res);
+----+------+-----+--------+
| id | name | age | dep_id |
+----+------+-----+--------+
| 5 | alex | 18 |   2 |
+----+------+-----+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
mysql> select @res;
+------+
| @res |
+------+
|  1 |
+------+
1 row in set (0.00 sec)
#在python中基于pymysql調(diào)用
cursor.callproc('p3',(3,0)) #0相當(dāng)于set @res=0
print(cursor.fetchall()) #查詢select的查詢結(jié)果
cursor.execute('select @_p3_0,@_p3_1;') #@p3_0代表第一個(gè)參數(shù),@p3_1代表第二個(gè)參數(shù),即返回值
print(cursor.fetchall())

帶有inout的例子

delimiter //
create procedure p4(
  inout n1 int
)
BEGIN
  select * from blog where id > n1;
  set n1 = 1;
END //
delimiter ;
#在mysql中調(diào)用
set @x=3;
call p4(@x);
select @x;
#在python中基于pymysql調(diào)用
cursor.callproc('p4',(3,))
print(cursor.fetchall()) #查詢select的查詢結(jié)果
cursor.execute('select @_p4_0;')
print(cursor.fetchall())

 事務(wù)

#介紹
delimiter //
      create procedure p4(
        out status int
      )
      BEGIN
        1. 聲明如果出現(xiàn)異常則執(zhí)行{
          set status = 1;
          rollback;
        }
        開始事務(wù)
          -- 由秦兵賬戶減去100
          -- 方少偉賬戶加90
          -- 張根賬戶加10
          commit;
        結(jié)束
        set status = 2;
      END //
      delimiter ;
#實(shí)現(xiàn)
delimiter //
create PROCEDURE p5(
  OUT p_return_code tinyint
)
BEGIN 
  DECLARE exit handler for sqlexception 
  BEGIN 
    -- ERROR 
    set p_return_code = 1; 
    rollback; 
  END; 
  DECLARE exit handler for sqlwarning 
  BEGIN 
    -- WARNING 
    set p_return_code = 2; 
    rollback; 
  END; 
  START TRANSACTION; 
    DELETE from tb1; #執(zhí)行失敗
    insert into blog(name,sub_time) values('yyy',now());
  COMMIT; 
  -- SUCCESS 
  set p_return_code = 0; #0代表執(zhí)行成功
END //
delimiter ;
#在mysql中調(diào)用存儲(chǔ)過程
set @res=123;
call p5(@res);
select @res;
#在python中基于pymysql調(diào)用存儲(chǔ)過程
cursor.callproc('p5',(123,))
print(cursor.fetchall()) #查詢select的查詢結(jié)果
cursor.execute('select @_p5_0;')
print(cursor.fetchall())

存儲(chǔ)過程的執(zhí)行

 mysql中執(zhí)行

-- 無參數(shù)
call proc_name()
-- 有參數(shù),全in
call proc_name(1,2)
-- 有參數(shù),有in,out,inout
set @t1=0;
set @t2=3;
call proc_name(1,2,@t1,@t2)

 pymsql中執(zhí)行

#!/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)
# 執(zhí)行存儲(chǔ)過程
cursor.callproc('p1', args=(1, 22, 3, 4))
# 獲取執(zhí)行完存儲(chǔ)的參數(shù)
cursor.execute("select @_p1_0,@_p1_1,@_p1_2,@_p1_3")
result = cursor.fetchall()
conn.commit()
cursor.close()
conn.close()
print(result)

刪除存儲(chǔ)過程

drop procedure proc_name;

看完上述內(nèi)容,你們掌握如何在mysql中使用存儲(chǔ)過程的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI