Table of Contents
1. Selection of transaction isolation mechanism
2. Table-level lock & row-level lock
3. Exclusive lock (Exclusive) and shared lock (Shared)
1. Test exclusive locks and shared locks between different transactions Compatibility
4. Serialization isolation level test
Home Database Mysql Tutorial How to use MySQL table locks, row locks, exclusive locks and shared locks

How to use MySQL table locks, row locks, exclusive locks and shared locks

Jun 03, 2023 am 10:49 AM
mysql

    1. Selection of transaction isolation mechanism

    • If we don’t care at all, use uncommitted read Transaction isolation mechanism, if these threads are allowed to operate the database concurrently, dirty reads (uncommitted data is read), non-repeatable reads (two query values ​​are different), phantom reads (two query data volumes are different), etc. Problem, data has the lowest security, the advantage is that the concurrency efficiency is very high, generally it will not be used

    • If we serialize (rely on Lock implementation), all transactions are sorted through locks. Although data security is improved, the concurrency efficiency is too low, and it is generally not used

    • So we generally use Committed Read and Repeatable Read These two isolation levels balance the security, consistency and concurrency efficiency of data, and are controlled by MVCC multi-version concurrency Implemented (MVCC is the principle of committed read and repeatable read, and lock is the principle of serialization)

    2. Table-level lock & row-level lock

    Table-level lock: lock the entire table. The overhead is small (because you don’t need to find the record of a certain row in the table to lock it. If you want to modify this table, you directly apply for the lock of this table), the lock is fast, and there will be no deadlock; the lock granularity is large, and lock conflicts will occur. The probability is high and the concurrency is low

    Row-level lock: Lock a row record. It is expensive (you need to find the corresponding record in the table, and there is a process of searching the table and index), locking is slow, and deadlock will occur; the locking granularity is the smallest, the probability of lock conflict is the lowest, and the concurrency is high

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    InnoDB storage engine supports transaction processing, the table supports row-level locking, and the concurrency capability is better

    1. InnoDB row lock is through the index on the index It is implemented by locking items instead of locking row records in the table. This means that InnoDB will only use row-level locks to retrieve data through index conditions. Otherwise InnoDB will use table locks

    2. Since InnoDB's row lock implementation is a lock added for index fields, not for row records, although different rows of the table under the InnoDB engine are accessed, if the same index field is used As a filter condition, lock conflicts will still occur, and can only be performed serially, not concurrently

    3. Even if indexes are used in SQL, after passing through the MySQL optimizer,if It is considered that full table scanning is more efficient than using indexes. At this time, the use of indexes will be abandoned. Therefore, row locks will not be used
      , but table locks will be used. For example, for some small tables , MySQL will not use the index

    3. Exclusive lock (Exclusive) and shared lock (Shared)

    • Exclusive lock, Also known as X lock, write lock

    • Shared lock, also known as S lock, read lock

    Read (SS) It is compatible, but reading and writing (SX, SX) and writing (XX) are mutually exclusive.

    There is the following relationship between adding X and S locks to transactions:

    • A transaction adds S lock to data object A. It can perform read operations on A but cannot perform update operations. During the locking period, other transactions can add S locks to A but cannot add X locks

    • If a transaction adds an X lock to data object A, it can read and update A. During the locking period, other transactions cannot add any locks to A

    Display locking: select … lock in share mode to force shared lock acquisition, select … for update to acquire exclusive lock

    1. Test exclusive locks and shared locks between different transactions Compatibility

    Let’s first check the SQL and content of the table

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    Check the isolation level:

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    ## First open a transaction and add an exclusive lock to the data with id=7

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    Then use another client to open the transaction

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    We use the service thread of another transaction to add an exclusive lock to the data with id=7, which is blocked.

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    We try to add an exclusive lock to the data with id=7. The shared lock is still blocked

    Summary: For data locks between different transactions, only SS locks can coexist, and XX, SX, and XS cannot coexist

    2. Test row lock addition On the index item

    the execution lock is added to the index tree

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    Use the non-indexed fields of the table as filter conditions

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    Transaction 2 now also wants to get the ranking of this record It locks, and it predictably fails; now transaction 2 obtains the exclusive lock of chenwei's record, try to see if it can succeed

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    InnoDB supports row locks , when using the primary key id as the filtering condition, transaction 1 and transaction 2 can successfully acquire locks for different rows. However, now we find that we cannot obtain the exclusive lock named chenwei. Why is this? Let’s explain:

    InnoDB’s row lock is implemented by locking index entries, rather than locking table row records

    And we Using name as a filter condition does not use an index, so naturally row locks will not be used, but table locks will be used. This means that InnoDB uses row-level locks only when data is retrieved through the index, otherwise InnoDB will use table locks!!!

    We add an index to the name field

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    We found that after adding an index to name, two transactions can obtain exclusive locks (for update) on different rows, once again proving that InnoDB's row locks are The

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    added to the index item is because the name now goes through the index. Through zhangsan, we find the id of the row record where it is located on the auxiliary index tree, which is 7, and then Go to the primary key index tree and obtain the exclusive lock of the corresponding row record (My personal guess is that the corresponding records in the auxiliary index tree and primary key index tree are locked)

    4. Serialization isolation level test

    (All transactions use exclusive locks or shared locks, no user is required to manually lock)

    Set the serialization isolation level

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    Two transactions can acquire shared locks at the same time (SS coexistence)

    How to use MySQL table locks, row locks, exclusive locks and shared locks


    Now let transaction 2 insert data

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    At this time, insert needs to add an exclusive lock, but since transaction 1 has added a shared lock to the entire table, transaction 2 can no longer successfully lock the table (SX does not coexist)

    rollback

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    Because we added an index to name, the above select is equivalent to adding a row shared lock to the data with name zhangsan

    Transaction 2 update

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    Transaction 2 cannot update because the entire table has been locked by the shared lock of transaction 1 at this time

    Transaction 2 looks for zhangsan on the auxiliary index tree , find the corresponding primary key value, and then go to the primary key index tree to find the corresponding record, but find that this row of records has been locked by a shared lock. Transaction 2 can obtain the shared lock, but cannot obtain the exclusive lock

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    Let’s try using the primary key index id to see if we can update

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    It’s still blocked, although the field behind where we now use id instead of name, but name also finds the corresponding primary key through the auxiliary index tree, and then finds the corresponding record on the primary key index tree, and the records on the primary key index tree are locked (My personal guess is that the auxiliary index tree and The data corresponding to the primary key index tree is locked)

    We updated the data with id=8 successfully. Only row locks are added to the row data with id 7, so we can successfully operate the data with id 8

    How to use MySQL table locks, row locks, exclusive locks and shared locks

    If there is an index, row locks are used; if there is no index, Then use table lock.

    Table-level locks or row-level locks refer to the granularity of the lock. Shared locks and exclusive locks refer to the nature of the lock. Whether it is a table lock or a row lock, there is a distinction between shared locks and exclusive locks

    The above is the detailed content of How to use MySQL table locks, row locks, exclusive locks and shared locks. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

    MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

    MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

    MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

    How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

    Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

    Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

    MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

    How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

    The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

    MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

    The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

    Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

    Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

    How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

    The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

    See all articles