select 语句for update作用

Select…For Update语句的语法与select语句相同,只是在select语句的后面加FOR UPDATE [NOWAIT]子句。

该语句用来锁定特定的行(如果有where子句,就是满足where条件的那些行)。当这些行被锁定后,其他会话可以选择这些行,但不能更改或删除这些行,直到该语句的事务被commit语句或rollback语句结束为止。

The FOR UPDATE clause lets you lock the selected rows so that other users cannot lock or update the rows until you end your transaction.

You can specify this clause only in a top-level SELECT statement, not in subqueries.

实验1: 验证在select ...for update之后,指定的数据行是否被锁定?

创建测试表

SQL> create table t1 (id number,name varchar2(32));

Table created.

SQL> insert into t1 values (1,'aa');

1 row created.

SQL> insert into t1 values (2,'bb');

1 row created.

SQL> commit;

Commit complete.

session1

SQL> select * from t1 where id=1 for update;

        ID NAME
---------- --------------------------------
         1 aa

session2

SQL> update t1 set name='aaaa' where id=1;

 此时,session2出现了锁等待现象,说明指定的数据行已被加锁。

实验2:select ... for update对指定的数据行加锁之后,是否影响其他数据行?

还是上面的测试表

session1

SQL> select * from t1 where id=1 for update;

        ID NAME
---------- --------------------------------
         1 aaaa
session2

SQL> update t1 set name='bbbb' where id=2;

1 row updated.  --说明session1并没有对id=2的数据行加锁

SQL> commit;

Commit complete.

事务结束之后,自动释放锁。结束事务的方式:

1. commit

2. rollback

3. 执行任何一条DDL(create/alter/drop)语句或DCL(grant/revoke)语句
————————————————
版权声明:本文为CSDN博主「码农A」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wo198711203217/java/article/details/28870779

浪漫家园,没事就来逛逛
原文地址:https://www.cnblogs.com/lovezbs/p/12865342.html