MySQL“锁表”的替代方案在存储过程中
如果行尚不存在,我需要将行插入到表中,并且我需要使用存储过程来执行此操作。因此,我需要选择检查该行是否已存在,然后进行插入。我想避免的是竞争条件,其中存储过程的两个调用者可能会看到该行不存在,然后都尝试插入该行。
我解决这个问题的第一个想法是锁定表,但不幸的是你不能在存储过程中发出 LOCK TABLE 。
我想避免在客户端 (C#) 捕获重复键插入异常。
有什么方法可以锁定表或替代解决方案吗?
I have a requirement to insert a row into a table if a row does not already exist, and I need to do this using a stored procedure. I therefore need to select to check if the row already exists, followed by an insert. What I want to avoid is a race condition where 2 callers of the stored procedure may see that the row doesn't exist and then both try to insert the row.
My first thoughts on solving this would be to lock the table, but unfortunately you cannot issue LOCK TABLE
in a stored procedure.
I want to avoid trapping a duplicate key insertion exception at the client (C#).
Any way of locking the table or alternative solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
示例 @thummper 答案来查看:
关于重复键忽略?
you can use
look on example @thummper answer:
On duplicate key ignore?
另一种选择是使用
,只要您有一个唯一的密钥,该插入发生两次就会违反该密钥,则不会再执行第二次。
Another option is to use
and as long as you have a unique key that would be violated by this insert happening twice, it won't be done a second time.