1 事务的介绍
create table mytest(
id int primary key,
name varchar(20)
);
– 开始事务
begin;
insert into mytest values(1,’test01’);
insert into mytest values(2,’test02’);
commit;
select * from mytest;
begin;
insert into mytest values(3, ‘test03’);
rollback;
select * from mytest;
begin;
insert into mytest values(4,’test04’);
savepoint s1;
insert into mytest values(5, ‘test05’);
savepoint s2;
insert into mytest values(6, ‘test06’);
rollback to s2;
commit;
select * from mytest;
– 禁止事务的自动提交
set autocommit = 0;
insert into mytest values(7, ‘test07’);
rollback;
select * from mytest;
set autocommit = 0;
insert into mytest values(8, ‘test08’);
commit;
2 通过InnoDB使用事务
/*利用事务的原理,完成借阅图书的一些操作:
1、向借阅信息表插入借阅记录
2、更新图书信息表的库存
3、更新读者信息表的余额
要求把借阅的相关操作看做一个整体,要么都成功,要么都失败。
比如:当库存=0或余额<=200时都不可以借书*/
delimiter //
create procedure borrowproc(cid char(18), bid int)
begin
declare store_num int;
declare money float(7,3);
select store into store_num from bookinfo where book_id = bid;
select balance into money from readerinfo where card_id = cid;
set autocommit = 0;
insert into borrowinfo values(bid,cid,curdate(), date_add(curdate(),interval 1 month),’否’);
update bookinfo set store = store - 1 where book_id = bid;
update readerinfo set balance = balance - (select price from bookinfo where book_id = bid)*0.05 where card_id = cid;
if store_num = 0 or money<=200 then
rollback;
else
commit;
end if;
end//
delimiter ;
select * from bookinfo;
select * from borrowinfo;
select * from readerinfo;
call borrowproc(‘210210199901014444’,20150202); 因为20150202库存为0,所以事务撤销
修改20150202库存为1,再执行
3 存储引擎的介绍