一 視圖
預先定義一種對應關係,如:temp_table <-----> select * from class where student_id >10,那麼這種對應關係叫做視圖。
它僅僅是一種對應關係,當以後調用時,是會重新從內存中拿右側的真正的表。視圖是臨時的,沒有真是存在內存中的。
創建視圖:
create view temp_table as select * from class where student_id >10
刪除視圖:
drop view temp_table
修改視圖:
alter view temp_table as .......
使用視圖:
select * from temp_table
二 存儲過程
先預先定義一個語句,如 tmp_table <==> select * from class where student_id >10, 當我們調用這個語句的時候會返回給我們結果,相當於函數。
創建存儲過程:
delimiter .. #delimiter 用來修改執行語句的結尾符,默認是';' ,這裏修改爲'..'
create procedure tmp_table()
begin
select * from class;
end ..
調用存儲過程:
call tmp_table()
存儲過程不推薦修改,就直接刪掉然後重建。
pymysql中使用存儲過程:
import pymysql connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='test', charset="utf8") cursor = connection.cursor(cursor=pymysql.cursors.DictCursor) cursor.callproc('tmp_table') result = cursor.fetchall() cursor.close() connection.close()
存儲過程可以接受參數,參數有三種:
a. in 用於傳入參數
b. out 用於返回值用
c. inout 即可以傳入又可以當返回值 創建帶有參數的存儲過程:
delimiter //
create procedure tmp_table(
in arg1 int,
out arg2 int,
inout arg3 int
)
begin
declare temp1 int;
declare temp2 int default 1;
set temp1 = 2;
set arg2 = temp1 + temp2;
set arg3 = arg2 + 10;
end//
delimiter ;
declare @arg2 int default 1; 聲明變量, 默認值爲1
declare @arg3 int default 1; 聲明變量, 默認值爲1
set @arg2 = 4; 給變量賦值
set @arg3 = 5
call tmp_table(1, @arg2, @arg3)
select @arg2,@arg3;
pymysql執行帶有參數的存儲過程:
import pymysql connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='test', charset="utf8") cursor = connection.cursor(cursor=pymysql.cursors.DictCursor) cursor.callproc('tmp_table', args=(1,22,33)) cursor.execute("select @_tmp_table_0,@_tmp_table_1,@_tmp_table_2") #取出返回參數的固定用法 print(cursor.fetchall()) connection.commit() cursor.close() connection.close()
例子:創建存儲過程:
pymysql執行代碼就是上面的,結果:
如果在存儲過程中有類似select * from '表名', 那麼只需在python代碼中,cursor.callproc()下面緊跟着執行 cursor.fetchall()就能拿到結果。
條件語句
delimiter \\ CREATE PROCEDURE proc_if () BEGIN declare i int default 0; if i = 1 THEN SELECT 1; ELSEIF i = 2 THEN SELECT 2; ELSE SELECT 7; END IF; END\\ delimiter ;
循環語句
delimiter \\ CREATE PROCEDURE proc_while () BEGIN DECLARE num INT ; SET num = 0 ; WHILE num < 10 DO SELECT num ; SET num = num + 1 ; END WHILE ; END\\ delimiter ;
delimiter \\ CREATE PROCEDURE proc_repeat () BEGIN DECLARE i INT ; SET i = 0 ; repeat select i; set i = i + 1; until i >= 5 end repeat; END\\ delimiter ;
BEGIN declare i int default 0; loop_label: loop set i=i+1; if i<8 then iterate loop_label; end if; if i>=10 then leave loop_label; end if; select i; end loop loop_label; END
動態執行SQL語句
delimiter \\ DROP PROCEDURE IF EXISTS proc_sql \\ CREATE PROCEDURE proc_sql () BEGIN declare p1 int; set p1 = 11; set @p1 = p1; PREPARE prod FROM 'select * from tb2 where nid > ?'; EXECUTE prod USING @p1; DEALLOCATE prepare prod; END\\ delimiter ; 動態執行SQL
以上語句參考了本片文章:https://www.cnblogs.com/wupeiqi/articles/5713323.html 十分感謝!