zoukankan      html  css  js  c++  java
  • sql server行级锁,排它锁,共享锁的使用

    1 如何锁一个表的某一行

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    SELECT * FROM table ROWLOCK WHERE id = 1

    2 锁定数据库的一个表

    SELECT * FROM table WITH (HOLDLOCK)

    加锁语句:
    sybase:
    update 表 set col1=col1 where 1=0 ;
    MSSQL:
    select col1 from 表 (tablockx) where 1=0 ;
    oracle:
    LOCK TABLE 表 IN EXCLUSIVE MODE ;
    加锁后其它人不可操作,直到加锁用户解锁,用commit或rollback解锁


    几个例子帮助大家加深印象
    设table1(A,B,C)
    A B C
    a1 b1 c1
    a2 b2 c2
    a3 b3 c3

    1)排它锁
    新建两个连接
    在第一个连接中执行以下语句
    begin tran
    update table1
    set A='aa'
    where B='b2'
    waitfor delay '00:00:30' --等待30秒
    commit tran
    在第二个连接中执行以下语句
    begin tran
    select * from table1
    where B='b2'
    commit tran

    若同时执行上述两个语句,则select查询必须等待update执行完毕才能执行即要等待30秒

    2)共享锁
    在第一个连接中执行以下语句
    begin tran
    select * from table1 holdlock -holdlock人为加锁
    where B='b2'
    waitfor delay '00:00:30' --等待30秒
    commit tran

    在第二个连接中执行以下语句
    begin tran
    select A,C from table1
    where B='b2'
    update table1
    set A='aa'
    where B='b2'
    commit tran

    若同时执行上述两个语句,则第二个连接中的select查询可以执行
    而update必须等待第一个事务释放共享锁转为排它锁后才能执行 即要等待30秒

    3)死锁
    增设table2(D,E)
    D E
    d1 e1
    d2 e2
    在第一个连接中执行以下语句
    begin tran
    update table1
    set A='aa'
    where B='b2'
    waitfor delay '00:00:30'
    update table2
    set D='d5'
    where E='e1'
    commit tran

    在第二个连接中执行以下语句
    begin tran
    update table2
    set D='d5'
    where E='e1'
    waitfor delay '00:00:10'
    update table1
    set A='aa'
    where B='b2'
    commit tran
  • 相关阅读:
    监控网页是否有变化
    设置开机自动启动进程
    nagios-调用脚本
    连接数据库出现10061错误
    小程序修改默认的radio样式
    小程序端,做类似于支付宝充值话费或流量的样式
    jq 在字符串中,去掉指定的元素
    vue 使用 proxyTable 解决跨域问题
    vue-cli 动态绑定图片失败
    vue-cli 使用 font-awesome 字体插件
  • 原文地址:https://www.cnblogs.com/cnlmjer/p/4099865.html
Copyright © 2011-2022 走看看