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
  • 相关阅读:
    人与人之间的本质
    如何让百度搜索不到
    js.prototype最深刻的理解
    调用函数不能用&
    浏览器的缓存就是关闭了浏览器任然存在
    Spring switch的使用
    thymeleaf如何遍历数据 each循环的使用
    spring 机制 扫描包
    Spring分层次建包
    如何使用thymeleaf显示控制传递过来的数据
  • 原文地址:https://www.cnblogs.com/cnlmjer/p/4099865.html
Copyright © 2011-2022 走看看