Oracle 数据库锁

数据库锁

锁的概念

Oracle中的锁的主要作用就是:防止并发事务对相同的资源(所谓资源是指 表、行、共享的数据结构、 数据字典行等)进行更改的时候,相互破坏。 锁有既有隐式的,也有显式的; 但某用户对某一批数据进行更改,而未提交之前,Oracle会隐式的进行加锁; 当然用户也可以显式的加锁,比如:select … from tableA where … for update NoWait

  1. create table testtab3
  2. ( Pk1 number ,
  3. field1 varchar2(200)
  4. );
  5. ALTER TABLE testtab3 ADD CONSTRAINT testtab3_PK PRIMARY KEY(Pk1) ;
  6. insert into testtab3 values (1, 'AAA');

查锁

①方式一

  1. select a.*, C.type, C.LMODE
  2. from v$locked_object a, all_objects b, v$lock c
  3. where a.OBJECT_ID = b.OBJECT_ID
  4. and a.SESSION_ID = c.SID
  5. and b.OBJECT_NAME = 'TESTTAB3'

②方式二

  1. select c.sid, c.serial#, c.username, c.osuser, b.owner, b.object_name, a.locked_mode, p.spid
  2. from v$locked_object a, dba_objects b, v$session c, v$process p
  3. where a.object_id = b.object_id
  4. and a.session_id = c.sid
  5. and c.paddr = p.addr ;

解锁

①解单锁

  1. alter system kill session 'sid, serial#' ;--填写对应的sid, serial#

②批量解锁

  1. declare cursor mycur is
  2. select b.sid,b.serial# from v$locked_object a,v$session b
  3. where a.session_id = b.sid group by b.sid,b.serial#;
  4. begin
  5. for cur in mycur
  6. loop
  7. execute immediate ( 'alter system kill session '''||cur.sid || ','|| cur.SERIAL# ||''' ');
  8. end loop;
  9. end;