MySQL学习-基础篇-事务

目录

p51-基础-事务-简介

p52-基础-事务-操作演示

p53-基础-事务-四大特性ACID

p54-基础-事务-并发事务问题

p55-基础-事务-并发事务演示及隔离级别

p56-基础-事务-小结

p57-基础篇总结


p51-基础-事务-简介

p52-基础-事务-操作演示

-- 数据准备
create table account(
    id int auto_increment primary key comment '主键ID',
    name varchar(10) comment '姓名',
    money int comment '余额'
) comment '账户表';
insert into account(id, name, money) VALUES (null,'张三',2000),(null,'李四',2000);

-- 1. 查询张三账户余额
select * from account where name = '张三';

-- 2. 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';


-- 3. 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';

-- 1. 查询张三账户余额
select * from account where name = '张三';

-- 2. 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';

程序抛出异常...

-- 3. 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';

 

select @@autocommit;

set @@autocommit = 0;    -- 设置为手动提交
-- 1. 查询张三账户余额
select * from account where name = '张三';

-- 2. 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';


-- 3. 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';


-- 提交事务
commit ;

 如果执行过程中异常,不提交事务,进行回滚事务,确保数据安全。

-- 回滚事务
rollback ;

--  方式二   ------------------
-- 转账操作(张三给李四转1000)
start transaction ;    -- 开启事务


-- 1. 查询张三账户余额
select * from account where name = '张三';

-- 2. 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';

程序运行报错...

-- 3. 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';


-- 提交事务
commit ;

-- 回滚事务
rollback ;

如果执行过程中出现异常,则不提交事务,进行回滚事务。

p53-基础-事务-四大特性ACID

 原子性:三个或者都执行成功,或者都执行失败

一致性:比如转账完成之后,两个人的余额加起来和原来加起来一样。

隔离性:两个并发的事务互不影响,独立进行

 持久性:数据是存储在磁盘当中的,一旦提交或者回滚,数据的改变是永久的。

p54-基础-事务-并发事务问题

p55-基础-事务-并发事务演示及隔离级别

p56-基础-事务-小结

p57-基础篇总结