資料庫:mysql內建功能-事務

來源:互聯網
上載者:User

標籤:err   name   art   code   rem   war   HERE   狀態   執行   

一 事物

事務用於將某些操作的多個SQL作為原子性操作,一旦有某一個出現錯誤,即可復原到原來的狀態,從而保證資料庫資料完整性。

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)

  

#介紹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())

  

 

資料庫:mysql內建功能-事務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.