C# 检查是否存在后插入MySQl时发生死锁
我使用的是C#,伪代码:C# 检查是否存在后插入MySQl时发生死锁,c#,mysql,C#,Mysql,我使用的是C#,伪代码: //option1:set the transaction as Serializable begin transaction () try{ //option2:add "for update" to the end of the select query string select id from table_name where name_col_1=binary 'new_name_1' and name_col_2=binary 'new_na
//option1:set the transaction as Serializable
begin transaction ()
try{
//option2:add "for update" to the end of the select query string
select id from table_name where name_col_1=binary 'new_name_1' and name_col_2=binary 'new_name_2'
if (exist) {rollback;return false;}
//dead lock exception when insert
insert into ...(id,...,name_col_1,name_col_2).. (default,...,'new_name_1','new_name_2')
commit;
return true;
}catch(){rollback;return false;}
id是自动递增主键
名称_col_1为varchar(100)
name_col_2是带有索引(500个字符)的varchar(5000)
当在多个客户端上同时运行代码时,使用上述代码、选项1或选项2(请检查上述代码中的注释),有时会引发“尝试获取锁时发现死锁;尝试重新启动事务”异常
这种简单的“不存在时插入”事务何时会触发死锁?因为如果不存在记录,则select无法锁定任何内容,并且在提交之前只有一个insert。如果记录存在,那么就回滚,死锁怎么会发生
注意:如果option1和option2都不存在,那么最终会有一些记录具有重复的“name_colu_1和name_colu_2”。查询会在MySQL中成功运行吗?@tcadidot0异常只会在竞争条件下随机发生。为什么不使用unique key和
INSERT。。。。在重复键上…
construction@SlavaRozhnev不支持该列为varchar(5000)唯一键。500字符的唯一键将防止插入某些不重复项。