Oracle数据库for update锁表现象及解决方法

一、锁表现象

用户一在PL/SQL或SQL Developer中执行如下语句:

select uid, username from t_user where uid = 2 for update;

并且没有点击提交事务,那么会产生行级锁。
那么用户二再在此表下执行for update语句时,就会出现卡死现象。

二、解决方案

2.1 用户操作

让用户一提交事务,便可以解锁。
用户二为了保险起见,可以选择回滚事务。

2.2 杀掉锁表进程

过程参考:https://www.cnblogs.com/soundcode/p/7156390.html

三、行级锁和表级锁

3.1 两种锁的概念

Oracle的锁机制主要分为行锁和表锁,行锁即锁定表中的某行数据,表锁锁定表中所有数据。锁定的数据不能插入,更新,删除,只能查询,语法 for update。锁的周期为一次数据提交,一次数据提交中可能会有多条SQL语句。
在大并发中为了保证某些数据的唯一性,常用到锁的机制,以下介绍行级锁和表级锁如何在大并发下保证数据的唯一性。

3.2 for update产生两种锁

3.2.1 行锁

线程1:

select * from user where id = 1 for update; 

线程2:
update user set name=’张三’ 堵塞
update user set name=’张三’ where id = 1 堵塞
update user set name=’张三’ where id = 2 正常
user表中id=1数据被锁定,其他进程无法修改user该条数据。但id=2所在行的数据仍可被修改。

3.2.2 表锁

线程1:

select * from user for update; 

线程2:
update user set name=’张三’ 堵塞
update user set name=’张三’ where id = 1 堵塞
user表被锁定,其他进程无法修改表中数据,只能查询。

猜你喜欢

转载自blog.csdn.net/qq_15329947/article/details/86648770