工作生活

mysql 事务原子性?——让你怀疑人生

2019-07-03  本文已影响0人  阿福德

前言

最近做项目中遇到一个情况,从日志中看到事务提交成功了,但出现一个事务中的数据存在部分成功,部分失败的情况。
难道mysql的事务不具有原子性了吗?我都要怀疑人生了。

实验一

事务1

begin trascation;                              --1
update table user set name='a' where id=1;     --1
update table user set name='b' where id=2;     --3
update table user set name='c' where id=3;     --5
commit ;                                       --5

事务2

begin trascation ;                             --2
update table user set desc='bb' where id=2;    --2
update table user set desc='aa' where id=1;    --4
update table user set desc='cc' where id=4;    --6
commit;                                       --6

上面两个事务,执行顺序如上面的序号。

现象

1、事务1提交成功,并且数据都正确。
2、事务2提交成功,但是只有最后一条update成功更新到了数据库中,desc=‘aa’与desc=‘bb’ 都没有更新成功。
3、当执行到4时,或出现死锁错误。
问题:我们可以看到事务2,发现是部分成功,部分失败。

分析

应该是mysql在检测到死锁后将事务2 kill掉了,后这条语句应该是自动提交(autocommit=true),如果死后这样,那我们试一下rollback, 看看将事务2的最后commit改为rollback试试,看看是否正正常rollback。

实验二

事务1

begin trascation;                              --1
update table user set name='a' where id=1;     --1
update table user set name='b' where id=2;     --3
update table user set name='c' where id=3;     --5
commit ;                                       --5

事务2

begin trascation ;                             --2
update table user set desc='bb' where id=2;    --2
update table user set desc='aa' where id=1;    --4
update table user set desc='cc' where id=4;    --6
rollback;                                     --6

上面两个事务,执行顺序如上面的序号。

现象

1、事务1提交成功,并且数据都正确。
2、事务2 rollback成功,没有数据会被更新到数据库中。
3、当执行到4时,或出现死锁错误。

疑问

mysql事务不能保证原子性了吗?
能解释这个问题的大侠,麻烦给我留言,感激不尽。

说明

使用的测试工具为:SQLyog
另外,在mysql服务端测试结果是,事务2不能回滚。(因为事务2的session被kill掉了。所以事务2的最后一句是自动提交的。)

上一篇 下一篇

猜你喜欢

热点阅读