mysql> SELECT @@session.tx_isolation; +------------------------+ | @@session.tx_isolation | +------------------------+ | REPEATABLE-READ | +------------------------+ 1 row in set
mysql> start transaction; Query OK, 0 rows affected
mysql> select * from test; +----+------+ | id | name | +----+------+ | 1 | aaa2 | | 2 | aaa2 | +----+------+ 2 rows in set
mysql> SELECT @@session.tx_isolation; +------------------------+ | @@session.tx_isolation | +------------------------+ | REPEATABLE-READ | +------------------------+ 1 row in set
mysql> start transaction; Query OK, 0 rows affected
mysql> select * from test; +----+------+ | id | name | +----+------+ | 1 | aaa2 | | 2 | aaa2 | +----+------+ 2 rows in set mysql> up^date test set name="bbb1" where id=1; Query OK, 1 row affected Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from test; +----+------+ | id | name | +----+------+ | 1 | bbb1 | | 2 | aaa2 | +----+------+ 2 rows in set 事务A正常更新OK~~注意,次数id为1的数据上有锁,并未释放~~ mysql> up^date test set name="bbb2" where id=1; 1205 - Lock wait timeout exceeded; try restarting transaction 事务B试图更新,结果等待锁超时~~ mysql> select * from test; +----+------+ | id | name | +----+------+ | 1 | bbb1 | | 2 | aaa2 | +----+------+ 2 rows in set
mysql> commit; Query OK, 0 rows affected 事务A提交了~~锁释放
mysql> select * from test; +----+------+ | id | name | +----+------+ | 1 | bbb1 | | 2 | aaa2 | +----+------+ 2 rows in set mysql> up^date test set name="bbb2" where id=1; Query OK, 1 row affected Rows matched: 1 Changed: 1 Warnings: 0 事务B这次更新成功了~~ mysql> select * from test; +----+------+ | id | name | +----+------+ | 1 | bbb1 | | 2 | aaa2 | +----+------+ 2 rows in set mysql> select * from test; +----+------+ | id | name | +----+------+ | 1 | bbb2 | | 2 | aaa2 | +----+------+ 2 rows in set
mysql> commit; Query OK, 0 rows affected 事务B提交~~ mysql> select * from test; +----+------+ | id | name | +----+------+ | 1 | bbb2 | | 2 | aaa2 | +----+------+ 2 rows in set mysql> select * from test; +----+------+ | id | name | +----+------+ | 1 | bbb2 | | 2 | aaa2 | +----+------+ 2 rows in set 结果双方可见~~ --------------------------------------- 结论: REPEATABLE-READ级别下: up^date会上锁,并持有,直到事务提交或回滚才会释放。 在此期间,其他事务无法更新相同的数据(锁影响到的数据) 所以,实际应用中,应该让事务尽快结束,否则会锁很长时间,影响太大。 减小事务的粒度。 mysql是通过在事务区间,给数据上锁,来实现(不能并发修改相同数据)的目的。 即多个事务可以并发处理,但是别更新相同的数据,如果是相同的,就得等人家的事务commit或rollback。
|