刚接触数据库。对数据库的锁比较迷惑。比如,我想选出一条记录,然后更新它。
那么如果我直接用update语句去更新它,数据库会自动的给该行记录加锁吧?可是如果我用(select * from A where id = 1 for update nowait;)这样加锁后
再用update语句去更新
和直接调用update语句去更新,让数据库为我加锁。这两者的区别是什么?

解决方案 »

  1.   

    我试过,select * from A where id = 1 for update nowait
    好像效果没有 select * from A where id = 1 for update 好,直接调用update语句去更新 ,就是不要用nowait就行了.
    nowait 是有条件的,就是在锁之前还可进行其它的操作。select * from A where id = 1 for update nowait
    command1
    command2
    commit;以上的效果也是锁表。
      

  2.   

    for update nowait  一般是用在加载数据前检测当前数据有没有被锁
    而  select * from  table for update 是把加载上来的数据锁住等当前事务提交后别人才可以更新
    使用 for update 没有提交事务时其它用户是不能更新的  
    此时 如果另一个用户也想更新当前数据就会出进入等待状态,直到当前事务提交
      

  3.   

    for update nowait  给当前记录加锁 ,如果记录已经加锁的话,则不需要等待锁释放,抛出一个异常
     for update 给当前记录加锁 ,如果记录已经加锁的话,则等待锁释放,锁释放以后,此语句才能加锁
      

  4.   


    多谢指教。。可是,好像是我没说明白。。
    我问的不是for update 和for update nowait的区别。
    而是select * from A where id = 1 for update nowait;-->update A set .. where id = 1
    和直接写update A set .. where id = 1的区别。
    我觉得这两种方式都可以为id为1的行加上锁,那么区别在哪里?