打牌 : da pai ge的个人主页
️个人专栏 : da pai ge的博客专栏
☁️宝剑锋从磨砺出,梅花香自苦寒来
准备测试表:
比如说,四十大盗把从阿里巴巴的账户上偷盗了2000元
假如在执行以上第一句SQL时,出现网络错误,或是数据库挂掉了,阿里巴巴的账户会减少2000,但是四十大盗的账户上就没有了增加的金额。
解决方案:使用事务来控制,保证以上两句SQL要么全部执行成功,要么全部执行失败。
事务指逻辑上的一组操作,组成这组操作的各个单元,要么全部成功,要么全部失败。
在不同的环境中,都可以有事务。对应在数据库中,就是数据库事务。
(1)开启事务:start transaction;
(2)执行多条SQL语句
(3)回滚或提交:rollback/commit;
explain select * from test_user where id_number=776655;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: test_user
type: ref
possible_keys: idx_test_user_id_number
key: idx_test_user_id_number <= key用到了idx_test_user_id_number
key_len: NULL
ref: const
rows: 1
Extra: Using where
1 row in set (0.00 sec)
drop table if exists accout;
create table accout(
id int primary key auto_increment,
name varchar(20) comment '账户名称',
money decimal(11,2) comment '金额'
);
insert into accout(name, money) values
('阿里巴巴', 5000),
('四十大盗', 1000);
-- 阿里巴巴账户减少2000
update accout set money=money-2000 where name = '阿里巴巴';
-- 四十大盗账户增加2000
update accout set money=money+2000 where name = '四十大盗';
说明:rollback即是全部失败,commit即是全部成功。