MySQL之事务
Posted 黑色彩虹
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL之事务相关的知识,希望对你有一定的参考价值。
事务用于将某些操作的多个SQL作为原子性操作,一旦有某一个出现错误,即可回滚到原来的状态,从而保证数据库数据完整性。举例说明:
create table user2( id int primary key auto_increment, name char(32), balance int ); insert into user2(name,balance) values (\'wsb\',1000), (\'egon\',1000), (\'ysb\',1000); #出现异常,回滚到初始状态 start transaction; update user2 set balance=900 where name=\'wsb\'; #买支付100元 update user2 set balance=1010 where name=\'egon\'; #中介拿走10元 uppdate user2 set balance=1090 where name=\'ysb\'; #卖家拿到90元,出现异常没有拿到 rollback; mysql> select * from user; +----+------+---------+ | id | name | balance | +----+------+---------+ | 1 | wsb | 1000 | | 2 | egon | 1000 | | 3 | ysb | 1000 | +----+------+---------+ rows in set (0.00 sec) #原子操作 start transaction; update user2 set balance=900 where name=\'wsb\'; #买支付100元 update user2 set balance=1010 where name=\'egon\'; #中介拿走10元 update user2 set balance=1090 where name=\'ysb\'; #卖家拿到90元 commit;
下面是操作:当ip_return_code为1时,表示异常,立马回滚。当为2时,出现警告,立马回滚原始状态。0表示成功
delimiter // create PROCEDURE b6( 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; insert into blog(name,sub_time) values(\'yyy\',now()); COMMIT; -- SUCCESS set p_return_code = 0; #0代表执行成功 END // delimiter ; set @res=123; call b6(@res); select @res;
select @res时返回0表示成功执行插入。此时,查询可以看到yyy已经成功插入blog表中
以上是关于MySQL之事务的主要内容,如果未能解决你的问题,请参考以下文章