简体   繁体   English

sql事务,为什么用户可以更新

[英]sql transactions, why user can update

I am learning transactions in mysql. 我正在学习mysql中的事务。 I cannot understand behaviour. 我无法理解行为。 Isolation level for my db is repeatable-read. 我的数据库的隔离级别是可重复读取的。 Database schema: 数据库模式:

creade database my_db;
use my_db;
create table locktest(
    id integer,
    val integer,
    primary key (id)
);
insert into locktest (id, val) values (3,6);

I created two users. 我创建了两个用户。 User1 does next: User1接下来要做的是:

start transaction;
select * from locktest where id = 3;

get id = 3, val = 6; 得到ID = 3,VAL = 6;

Then, user2 updates: 然后,user2更新:

update locktest set val = 7 where id = 3;
select * from locktest where id = 3;

result is id = 3, val = 7; 结果是id = 3,val = 7;

user1 selects: user1选择:

select * from locktest where id = 3;

id = 3, val = 7 id = 3,val = 7

So, my question why can user2 update the table, should not be it locked by user1? 因此,我的问题是为什么user2可以更新表,而不应该被user1锁定? And why in last select from user1 it gets updated values, should not be it consistent according to repeatable read isolation level ? 以及为什么在user1的最后一次选择中它会获取更新的值,根据可重复的读取隔离级别,它是否不一致?

Do you need innodb, see this answer . 您是否需要innodb,请参见此答案

You should enclose your SQL operation into transactions to ensure isolation, its enough to enclose User 1 operations for your tests. 您应该将SQL操作包含在事务中以确保隔离,该操作足以将User 1操作包含在测试中。 Remember to execute commands in two separate sessions, for example opening MySQL tool for twice, you can't test this with phpmyadmin: 记住要在两个单独的会话中执行命令,例如两次打开MySQL工具,您不能使用phpmyadmin对此进行测试:

User 1:                                         User 2:
SET SESSION TRANSACTION 
 ISOLATION LEVEL
 REPEATABLE READ;

START TRANSACTION;                              START TRANSACTION;

select * 
 from locktest where id = 3;

                                                update locktest 
                                                  set val = 7 where id = 3;
                                                select * from locktest 
                                                  where id = 3;

select * 
 from locktest where id = 3;

--Result must be the same than
--previus query.

COMMIT;

                                                COMMIT;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM