简体   繁体   English

选择用ruby oci8更新

[英]select for update with ruby oci8

how do I do a 'select for update' and then 'update' the row using ruby oci8. 如何执行“选择更新”,然后使用ruby oci8“更新”行。

I have two fields counter1 and counter2 in a table which has only 1 record. 我在只有1条记录的表中有两个字段counter1和counter2。 I want to select the values from this table and then increment them by locking the row using select for update. 我想从该表中选择值,然后通过使用select for update锁定行来增加它们。

thanks. 谢谢。

You need to make sure that autocommit is set to false on your connection. 您需要确保在连接上将autocommit设置为false。 This is the key. 这是关键。 Then you would do the following steps: 然后,您将执行以下步骤:

  1. Do your select with the for update clause on the end (select column1, column2 from mytable for update). 在末尾使用for update子句进行选择(从mytable中选择column1,column2进行更新)。 This will lock the row. 这将锁定行。

  2. Perform your Update query. 执行更新查询。

  3. Issue an explicit commit which would release the lock on the row. 发出明确的提交,这将释放该行上的锁。

Of course remember that locking the row just locks it from modification. 当然,请记住,锁定行只是将其锁定而无法修改。 Another session could still query those rows. 另一个会话仍可以查询这些行。 For example if this was an ID and the way to fetch a new ID was to query the table doing a select max(id) + 1 from table . 例如,如果这是一个ID,而获取新ID的方法是查询表,并从table中执行select max(id) + 1 from table Locking the row would not prevent another session from doing this select. 锁定该行不会阻止另一个会话执行此选择。

Better yet would be to skip the select and update the records in place and use the returning clause to return to you the new updated values. 更好的方法是跳过选择并更新记录,并使用returning子句向您返回新的更新值。 I have never done it in Ruby OCI8, so I'm not sure if it supports that feature. 我从未在Ruby OCI8中做到这一点,所以不确定它是否支持该功能。 The docs for that clause in an update are here: 更新中该子句的文档在这里:

http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10007.htm#i2126358 http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10007.htm#i2126358

select_stmt = conn.prepare('select * from table_name for update')
select_stmt.exec
while row = select_stmt.fetch
  conn.exec('update table_name set col = :1 where rowid = :2', 'val', select_stmt.rowid)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM