什么是locking reading 说白了就是在query的同时对相应的数据进行锁定,以便于保持事物的完整性
locking reading的两种形式 select ... lock in share mode: 在查询的时候给数据加一个读写锁。在事务提交前,其他的事物只能读取当前查询出的数据,但不能修改
select ... for update:将读数据的行为判断为写(update)行为,其作用效果根据不同的隔离级别和有所不同。
注意 select ... for update只有在autocommit = 0 的时候才能生效 只能适用于支持acid的数据引擎,如innodb 举例 一个简单的例子,把数据从数据库中取出加1再 存入。隔离级别为默认的repeatable read。
start transaction; select quantity from selectforupdate where id = 3 limit 1 into @a; set @a = @a + 1; update selectforupdate set quantity = @a where id = 3; commit;
使用mysql自带的mysqlslat做30线程的测试,使用 select * from testsql.selectforupdate; 获取结果。
如果在select语句中没有 for update,最终的结果会随机的变动,在我这里是2或3。如果使用select quantity from selectforupdate where id = 3 limit 1 into @a for update;,最终的结果为 30
