1. 程式人生 > >Mysql(代碼記憶)

Mysql(代碼記憶)

format roc 執行 記憶 create prim 時間 cursor date

1.視圖

#修改視圖,原始表也跟著改
mysql> select * from course;
+-----+--------+------------+
| cid | cname  | teacher_id |
+-----+--------+------------+
|   1 | 生物   |          1 |
|   2 | 物理   |          2 |
|   3 | 體育   |          3 |
|   4 | 美術   |          2 |
+-----+--------+------------+
rows in set (0.00 sec)

mysql
> create view course_view as select * from course; #創建表course的視圖 Query OK, 0 rows affected (0.52 sec) mysql> select * from course_view; +-----+--------+------------+ | cid | cname | teacher_id | +-----+--------+------------+ | 1 | 生物 | 1 | | 2 | 物理 | 2 | | 3 | 體育 | 3 | | 4 | 美術 | 2 | +-----+--------+------------+ rows
in set (0.00 sec) mysql> update course_view set cname=xxx; #更新視圖中的數據 Query OK, 4 rows affected (0.04 sec) Rows matched: 4 Changed: 4 Warnings: 0 mysql> insert into course_view values(5,yyy,2); #往視圖中插入數據 Query OK, 1 row affected (0.03 sec) mysql> select * from course; #發現原始表的記錄也跟著修改了 +-----+-------+------------+ | cid | cname | teacher_id | +-----+-------+------------+ | 1 | xxx | 1 | | 2 | xxx | 2 | | 3 | xxx | 3 | | 4 | xxx | 2 | | 5 | yyy | 2 | +-----+-------+------------+ rows
in set (0.00 sec)

2.觸發器

#準備表
CREATE TABLE cmd (
    id INT PRIMARY KEY auto_increment,
    USER CHAR (32),
    priv CHAR (10),
    cmd CHAR (64),
    sub_time datetime, #提交時間
    success enum (yes, no) #0代表執行失敗
);

CREATE TABLE errlog (
    id INT PRIMARY KEY auto_increment,
    err_cmd CHAR (64),
    err_time datetime
);

#創建觸發器
delimiter //
CREATE TRIGGER tri_after_insert_cmd AFTER INSERT ON cmd FOR EACH ROW
BEGIN
    IF NEW.success = no THEN #等值判斷只有一個等號
            INSERT INTO errlog(err_cmd, err_time) VALUES(NEW.cmd, NEW.sub_time) ; #必須加分號
      END IF ; #必須加分號
END//
delimiter ;


#往表cmd中插入記錄,觸發觸發器,根據IF的條件決定是否插入錯誤日誌
INSERT INTO cmd (
    USER,
    priv,
    cmd,
    sub_time,
    success
)
VALUES
    (egon,0755,ls -l /etc,NOW(),yes),
    (egon,0755,cat /etc/passwd,NOW(),no),
    (egon,0755,useradd xxx,NOW(),no),
    (egon,0755,ps aux,NOW(),yes);


#查詢錯誤日誌,發現有兩條
mysql> select * from errlog;
+----+-----------------+---------------------+
| id | err_cmd         | err_time            |
+----+-----------------+---------------------+
|  1 | cat /etc/passwd | 2017-09-14 22:18:48 |
|  2 | useradd xxx     | 2017-09-14 22:18:48 |
+----+-----------------+---------------------+
rows in set (0.00 sec)

3.事務

create table user(
id int primary key auto_increment,
name char(32),
balance int
);

insert into user(name,balance)
values
(wsb,1000),
(egon,1000),
(ysb,1000);

#原子操作
start transaction;
update user set balance=900 where name=wsb; #買支付100元
update user set balance=1010 where name=egon; #中介拿走10元
update user set balance=1090 where name=ysb; #賣家拿到90元
commit;

#出現異常,回滾到初始狀態
start transaction;
update user set balance=900 where name=wsb; #買支付100元
update user set balance=1010 where name=egon; #中介拿走10元
uppdate user set balance=1090 where name=ysb; #賣家拿到90元,出現異常沒有拿到
rollback;
commit;
mysql> select * from user;
+----+------+---------+
| id | name | balance |
+----+------+---------+
|  1 | wsb  |    1000 |
|  2 | egon |    1000 |
|  3 | ysb  |    1000 |
+----+------+---------+
rows in set (0.00 sec)

4.存儲過程

#方式一:
    MySQL:存儲過程
    程序:調用存儲過程

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

#方式三:
    MySQL:
    程序:類和對象,即ORM(本質還是純SQL語句)
#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:既可以傳入又可以返回
#介紹
delimiter //
            create procedure p4(
                out status int
            )
            BEGIN
                1. 聲明如果出現異常則執行{
                    set status = 1;
                    rollback;
                }
                   
                開始事務
                    -- 由秦兵賬戶減去100
                    -- 方少偉賬戶加90
                    -- 張根賬戶加10
                    commit;
                結束
                
                set status = 2;
                
                
            END //
            delimiter ;

#實現
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; #執行失敗
        insert into blog(name,sub_time) values(yyy,now());
    COMMIT; 

    -- SUCCESS 
    set p_return_code = 0; #0代表執行成功

END //
delimiter ;

#在mysql中調用存儲過程
set @res=123;
call p5(@res);
select @res;

#在python中基於pymysql調用存儲過程
cursor.callproc(p5,(123,))
print(cursor.fetchall()) #查詢select的查詢結果

cursor.execute(select @_p5_0;)
print(cursor.fetchall())

事務

在python中的具體調用方法

-- 無參數
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執行存儲過程

date_formit

#1 基本使用
mysql> SELECT DATE_FORMAT(2009-10-04 22:23:00, %W %M %Y);
        -> Sunday October 2009
mysql> SELECT DATE_FORMAT(2007-10-04 22:23:00, %H:%i:%s);
        -> 22:23:00
mysql> SELECT DATE_FORMAT(1900-10-04 22:23:00,
    ->                 %D %y %a %d %m %b %j);
        -> 4th 00 Thu 04 10 Oct 277
mysql> SELECT DATE_FORMAT(1997-10-04 22:23:00,
    ->                 %H %k %I %r %T %S %w);
        -> 22 22 10 10:23:00 PM 22:23:00 00 6
mysql> SELECT DATE_FORMAT(1999-01-01, %X %V);
        -> 1998 52
mysql> SELECT DATE_FORMAT(2006-06-00, %d);
        -> 00


#2 準備表和記錄
CREATE TABLE blog (
    id INT PRIMARY KEY auto_increment,
    NAME CHAR (32),
    sub_time datetime
);

INSERT INTO blog (NAME, sub_time)
VALUES
    (第1篇,2015-03-01 11:31:21),
    (第2篇,2015-03-11 16:31:21),
    (第3篇,2016-07-01 10:21:31),
    (第4篇,2016-07-22 09:23:21),
    (第5篇,2016-07-23 10:11:11),
    (第6篇,2016-07-25 11:21:31),
    (第7篇,2017-03-01 15:33:21),
    (第8篇,2017-03-01 17:32:21),
    (第9篇,2017-03-01 18:31:21);

#3. 提取sub_time字段的值,按照格式後的結果即"年月"來分組
SELECT DATE_FORMAT(sub_time,%Y-%m),COUNT(1) FROM blog GROUP BY DATE_FORMAT(sub_time,%Y-%m);

#結果
+-------------------------------+----------+
| DATE_FORMAT(sub_time,%Y-%m) | COUNT(1) |
+-------------------------------+----------+
| 2015-03                       |        2 |
| 2016-07                       |        4 |
| 2017-03                       |        3 |
+-------------------------------+----------+
rows in set (0.00 sec)

需要掌握函數:date_format

Mysql(代碼記憶)