MySQL事物

事务是一组操作的集合,它是一个不可分割的工作单位,事务会把所有的操作作为一个整体一起向系 统提交或撤销操作请求,即这些操作要么同时成功,要么同时失败。

SELECT @@autocommit ;

SET @@autocommit = 0 ;

创建表没问题
create table account(
id int primary key AUTO_INCREMENT comment 'ID',
name varchar(10) comment '姓名',
money double(10,2) comment '余额'
) comment '账户表';
插入已执行,但是没数据。
insert into account(name, money) VALUES ('张三',2000), ('李四',2000);
提交后数据显示
commit ;

注意:上述的这种方式,我们是修改了事务的自动提交行为, 把默认的自动提交修改为了手动提 交, 此时我们执行的DML语句都不会提交, 需要手动的执行commit进行提交。(这里DML就是增、删、改数据)

默认MySQL的事务是自动提交的,也就是说,当执行完一条DML语句时,MySQL会立即隐 式的提交事务。

事务四大特性

begin;

select * from account where name = '张三';

update account set money = money - 1000 where name = '张三';

update account set money = money + 1000 where name = '李四';

没有改变

update account set money = money + 1000 where name = '李四';

没有改变

commit ;


原子性(Atomicity):事务是不可分割的最小操作单元,要么全部成功,要么全部失败。

从开始begin到最后commit,要么都成功,要么rollback回滚。


一致性(Consistency):事务完成时,必须使所有的数据都保持一致状态。

张三和李四加起来一共4000元,最后无论谁增谁减最后都是4000元。

隔离性(Isolation):数据库系统提供的隔离机制,保证事务在不受外部并发操作影响的独立 环境下运行。


持久性(Durability):事务一旦提交或回滚,它对数据库中的数据的改变就是永久的。 上述就是事务的四大特性,简称ACID。

commit之后,数据的改动是永久生效的,除非再次改动。

事务隔离级别

注意:事务隔离级别越高,数据越安全,但是性能越低。

SELECT @@TRANSACTION_ISOLATION;

系统默认隔离级别

Read uncommitted

读未提交容易造成脏读

set session transaction isolation level read uncommitted ;
select money from account where name = '张三';

update account set money = money - 1000 where name = '张三';(未提交)

select money from account where name = '张三';(但是查到未提交的数据)脏读

rollback回滚
select money from account where name = '张三';

Read committed

update account set money = money - 1000 where name = '张三';datagrip端
select money from account where name = '张三';cmd端查看两次提交和未提交

提交前和未提交前

Repeatable Read(默认)

start transaction ;
select * from account;
insert into account(id,name,money)values (3,'王五',2000);
commit ;
幻读

展开阅读全文

页面更新:2024-05-12

标签:持久性   不可分割   余额   原子   语句   特性   事物   级别   事务   操作   数据

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top