资讯专栏INFORMATION COLUMN

深度完整的了解MySQL锁

asoren / 2207人阅读

摘要:今天就讲讲的锁主讲的悲观锁和乐观锁官方意思就是你普通的查询,并有保护功能,也就是没有锁,会出现事务执行的时候,数据出现错乱,然而提供了引擎支持种锁机制。

今天就讲讲MySQL的锁

主讲:Mysql的悲观锁 和 乐观锁
官方:If you query data and then insert or update related data within the same transaction, the regular SELECT statement does not give enough protection. Other transactions can update or delete the same rows you just queried. InnoDB supports two types of locking reads that offer extra safety:
意思就是你普通的查询sql,并有保护功能,也就是没有锁,会出现事务执行的时候,数据出现错乱,然而MySQL提供了innodb引擎支持2种锁机制。

1.悲观锁:
    概念:
        a) 官方:For index records the search encounters, SELECT … FOR UPDATE locks the rows and any associated index entries, the same as if you issued an UPDATE statement for those rows. Other transactions are blocked from updating those rows, from doing SELECT … LOCK IN SHARE MODE, or from reading the data in certain transaction isolation levels. Consistent reads ignore any locks set on the records that exist in the read view. (Old versions of a record cannot be locked; they are reconstructed by applying undo logs on an in-memory copy of the record.
        b) 简单粗俗点就是直接占为己有,等自己用完了才给别人去使用,这种能保证数据的操作不会出错,获得这个锁的人可以修改,查询数据,其他人则什么操作都做不了。
    使用语法:select * from tb for update

2.乐观锁:
    概念:
        a) 官方:SELECT ... LOCK IN SHARE MODE sets a shared mode lock on the rows read. A shared mode lock enables other sessions to read the rows but not to modify them. The rows read are the latest available, so if they belong to another transaction that has not yet committed, the read blocks until that transaction ends.
        b)简单点说就是进行宽松锁的限制,也就是别人也可以叠加锁上去,然后大家也都可以进行select操作,但不能进行update或者delete操作(也就是修改操作),哪怕大家的事务都还没提交,大家都可以普通的 select 都是可以查询出数据的一定要注意:这个时候select是没有影响的
    使用语法:select...lock in share mode

下面内容一定要注意:
All locks set by LOCK IN SHARE MODE and FOR UPDATE queries are released when the transaction is committed or rolled back.

Note
Locking of rows for update using SELECT FOR UPDATE only applies when autocommit is disabled (either by beginning transaction with START TRANSACTION or by setting autocommit to 0. If autocommit is enabled, the rows matching the specification are not locked.

所有的锁都在事务回滚或者结束后释放。
注意:
使用select..for update 进行行锁,只有在禁用autocommit的时候生效(或者在START TRANSACTION 或者 设置 autocommit为0.)如果autocommit是启用的,那这一行的for update是不会生效的。

        更多精彩内容也可以关注此二维码:
        

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/29128.html

相关文章

  • 深度完整了解MySQL

    摘要:今天就讲讲的锁主讲的悲观锁和乐观锁官方意思就是你普通的查询,并有保护功能,也就是没有锁,会出现事务执行的时候,数据出现错乱,然而提供了引擎支持种锁机制。 今天就讲讲MySQL的锁 主讲:Mysql的悲观锁 和 乐观锁官方:If you query data and then insert or update related data within the same transactio...

    RobinTang 评论0 收藏0
  • database

    摘要:它是第一个把数据分布在全球范围内的系统,并且支持外部一致性的分布式事务。目的是使得开发者阅读之后,能对项目有一个初步了解,更好的参与进入的开发中。深度探索数据库并发控制技术并发控制技术是数据库事务处理的核心技术。 存储过程高级篇 讲解了一些存储过程的高级特性,包括 cursor、schema、控制语句、事务等。 数据库索引与事务管理 本篇文章为对数据库知识的查缺补漏,从索引,事务管理,...

    csRyan 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<