深度完整的瞭解MySQL鎖

今天就講講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種鎖機制。sql

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 updatesession

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 modeapp

下面內容必定要注意:
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.ci

全部的鎖都在事務回滾或者結束後釋放。
注意:
使用select..for update 進行行鎖,只有在禁用autocommit的時候生效(或者在START TRANSACTION 或者 設置 autocommit爲0.)若是autocommit是啓用的,那這一行的for update是不會生效的。it

        更多精彩內容也能夠關注此二維碼:
       io

相關文章
相關標籤/搜索