sql中的事物

发布时间 2023-04-28 19:40:36作者: 爱豆技术部
sql中的事物
MySQL默认的是repeatable read
首先要开启事物
start transaction;
第二 所有的修改删除都为一个事物
当没有提交的时候只是操作的 缓存中的数据,
*此时查询的会存在 幻读 (读取的都是为修改的数据)
第三 在未提交前可以回滚事物 rollback;
第四提交 commit; 会默认关闭此次事物

 

create table account(
      id int primary key auto_increment,
      uname varchar(10) not null,
      balance double
);

-- 查看账户表:
select * from account;
-- 在表中插入数据:
insert into account values (null,'丽丽',2000),(null,'小刚',2000);

-- 此时是执行的两个事物 影响了两行
UPDATE account set balance = balance +200 where id =1;
UPDATE account set balance = balance -200 where id =2

-- 手动开启事务:
start transaction;

UPDATE account set balance = balance +200 where id =1;
UPDATE account set balance = balance -200 where id =2

-- 手动回滚:刚才执行的操作全部取消:
-- 在回滚和提交之前,数据库中的数据都是操作的缓存中的数据,而不是数据库的真实数据
rollback;
-- 手动提交:
commit;