如何锁定单行
我有一个带有字段 lastusedecnumber
的 user
表。
我需要访问并递增 lastusedecnumber
。
在访问期间,我需要锁定该特定用户行(而不是整个表)。
我该怎么做?
表类型为MyISAM
。
I have a user
table with field lastusedecnumber
.
I need to access and increment lastusedecnumber
.
During that accessing time I need to lock that particular user row (not the entire table).
How do I do this?
The table type is MyISAM
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不想将整个数据库从 myisam 转换。所以我只是尝试创建一个根据我想要锁定的记录的 id 命名的新表。如果创建表成功,则执行我的工作并在最后删除该表。如果建表不成功,则停止。
I didn't feel like converting my whole database from myisam. So I simply try to create a new table named based on the id of the record I want to lock. If create table is successful, do my work and delete the table at the end. If create table not successful, stop.
更好的解决方法是创建一个包含时间戳的列。每当您想要锁定该行时,请将其更新为当前时间。要解锁,请更新到至少 x 分钟前的时间。然后检查其是否已锁定,检查时间戳是否至少为 x 分钟。
这样,如果进程崩溃(或者用户从未完成其操作),锁定将在 x 分钟后有效过期。
A better workaround is to create a column containing a timestamp. Whenever you want to lock the row you update it to the current time. To unlock, update to a time at least x minutes in the past. Then to check if its locked check that the time stamp is at least x minutes old.
This way if the process crashes (or the user never completes their operation) the lock effectively expires after x minutes.
MySQL 仅使用 MyISAM 表的表级锁定。如果可以的话,切换到 InnoDB 进行行级锁定。
以下是 MySQL 站点的链接,该站点描述了 SQL 语句为 InnoDB 表设置的锁。
http://dev.mysql.com/doc/refman /5.0/en/innodb-locks-set.html
MySQL uses only table-level locking from MyISAM tables. If you can, switch to InnoDB for row-level locking.
Here's a link to the MySQL site describing Locks set by SQL Statements for InnoDB tables.
http://dev.mysql.com/doc/refman/5.0/en/innodb-locks-set.html
有点晚了,但希望它能帮助某人:
将为您提供lastusedecnumber的原子增量,并能够使用
SELECT LAST_INSERT_ID()
读取lastusedecnumber
字段的新值(增量后) 。Kind of late, but hope it will help someone:
Will give you atomic increment of lastusedecnumber and ability to read new value of
lastusedecnumber
field (after increment) usingSELECT LAST_INSERT_ID()
.作为解决方法,您可以向表中添加一列,例如
locked TINYINT(1)
- 每当您希望锁定该行时,请将其设置为1
。当您现在尝试访问此行时,您要做的第一件事是检查是否设置了locked
字段。要解锁该行,只需再次将其设置为
0
即可。不太好,但是一个非常简单的解决方法。As a workaround you could add a column to your table, like
locked TINYINT(1)
- whenever you want the row to be locked you set it to1
. When you now try to access this row, the first thing you do is check if thelocked
fields is set.To unlock the row, simply set it to
0
again. Not nice but a really simple workaround.