且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止重复插入和死锁读取

更新时间:2023-01-22 16:09:36

在查询中,尝试更新并评估更改的记录数。如果它是< 1,然后插入。



我认为秘诀就是妥善处理异常。将对ExecuteNonQuery的调用放入while循环中,并在没有异常时退出该循环。在再次尝试查询之前,请不要忘记包括短暂的延迟(500毫秒左右)。



编辑============= ==============



这是我在MS-SQL中所做的,MYSQL应该是类似的:



In the query, try to update and evaluate the number of records changed. If it's < 1, then do an insert.

I think the secret is to properly handle exceptions. Put your call to ExecuteNonQuery into a while loop and exit that loop when there's no exception. Don't forget to include a short delay (500ms or so) before attempting the query again.

EDIT ===========================

This is what I do in MS-SQL, and MYSQL should be similar:

UPDATE [table]
SET [field1]=@value1
    ...
WHERE [field2] = @value2
IF (@@ROWCOUNT = 0)
    INSERT...





当然,您可能需要将锁定/解锁和交易声明放在适当的位置。



Of course, you probably need to put your lock/unlock and transaction statements in the appropriate places.