开发者

MySQL Alternative to "Lock Table" in Stored Procedure

I have a requirement to insert a row into a tab开发者_开发技巧le 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?


you can use

insert into ... on duplicate key

look on example @thummper answer:

On duplicate key ignore?


Another option is to use

INSERT IGNORE INTO ... 

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜