最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

MySQL for update鎖表還是鎖行校驗(過程詳解)

 更新時間:2024年02月02日 11:08:58   作者:c103363  
在MySQL中,使用for update子句可以對查詢結(jié)果集進行行級鎖定,以便在事務(wù)中對這些行進行更新或者防止其他事務(wù)對這些行進行修改,這篇文章主要介紹了MySQL for update鎖表還是鎖行校驗,需要的朋友可以參考下

select * from user where id = 1 for update ;

1. for update作用

在MySQL中,使用for update子句可以對查詢結(jié)果集進行行級鎖定,以便在事務(wù)中對這些行進行更新或者防止其他事務(wù)對這些行進行修改。

當(dāng)使用for update時,鎖定行的方式取決于where中的字段是否具有索引,而不是唯一索引。如果where

條件中的字段具有索引(無論是普通索引還是唯一索引),MySQL將鎖定與查詢結(jié)果集匹配的行,如果where中的字段沒有索引MySQL將鎖表

2. 擼代碼證明結(jié)果

創(chuàng)建一張表

其中id是主鍵,user_name建立索引

create table if not exists user
(
  id        int auto_increment comment '主鍵ID'
  primary key,
  user_name varchar(32) null comment '用戶名',
  password  varchar(64) null comment '密碼',
  phone     varchar(11) null comment '手機號'
);
create index user_user_name_index
    on test1.user (user_name);

插入三條數(shù)據(jù)

INSERT INTO user (id, user_name, password, phone) VALUES (1, '小明', '123', '13123920201');
INSERT INTO user (id, user_name, password, phone) VALUES (2, '小王', '1234', '13123920202');
INSERT INTO user (id, user_name, password, phone) VALUES (3, '小狗', '12345', '13123920203');

begin:表示開啟一個事物

commit:表示提交事物

新開3個查詢窗口

窗口1

begin;
select * from user where id = 1 for update ;
commit;

窗口2

begin;
select * from user where id = 1 for update ;
commit;

窗口3

begin;
select * from user where id = 2 for update ;
commit;

a. 查詢帶普唯一引字段

步驟1: 窗口1執(zhí)行下面代碼

begin;
select * from user where id = 1 for update ;

結(jié)果如下

img

這時id = 1的行應(yīng)該被鎖住了

步驟2: 窗口2執(zhí)行下面代碼

begin;
select * from user where id = 1 for update ;

結(jié)果如下,一直在等待

img

最后報鎖超時錯誤

img

證明id = 1的行被鎖住了

步驟3:

查詢id=2的數(shù)據(jù)

begin;
select * from user where id = 2 for update ;

可以查到結(jié)果

img

說明select * from user where id = 1 for update ;只鎖了id = 1的行,id = 2行沒有被鎖

步驟4:

窗口1執(zhí)行下面代碼

commit;

結(jié)果如下

img

窗口2再執(zhí)行下面代碼

begin;
select * from user where id = 1 for update ;

這時就可以查出結(jié)果來了

img

說明id = 1行鎖被釋放,窗口2就可以查到結(jié)果了

證明唯一索引鎖行

b. 查詢帶普通索引字段

窗口1

begin;
select * from user where user_name = '小明' for update ;

img

窗口2

begin;
select * from user where user_name = '小王' for update ;

img

證明普通索引時鎖行

c. 查詢沒索引字段

窗口1:

begin;
select * from user where phone = 13123920201 for update ;

img

窗口2:

begin;
select * from user where id = 2 for update ;

img

一直再查詢

img

鎖等待超時

證明沒索引時鎖表

到此這篇關(guān)于MySQL for update鎖表還是鎖行校驗的文章就介紹到這了,更多相關(guān)MySQL for update鎖表還是鎖行內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

沙河市| 甘德县| 鹰潭市| 江安县| 黄陵县| 蓬安县| 林西县| 盐池县| 虎林市| 房产| 长丰县| 凌海市| 金山区| 永吉县| 康乐县| 米易县| 洪泽县| 且末县| 大化| 兴业县| 大丰市| 岑巩县| 江都市| 屏山县| 涟水县| 克拉玛依市| 梓潼县| 会宁县| 舒城县| 山阳县| 额尔古纳市| 四子王旗| 施甸县| 沁源县| 新宁县| 东乡族自治县| 徐闻县| 淮北市| 祁东县| 晴隆县| 湟源县|