简体   繁体   English

mysql唯一索引用作java中的异常处理方法

[英]mysql unique index used as exception handling method in java

I want to know whether is it a good idea to catch exception based on unique index of sql in java. 我想知道基于java中sql的唯一索引捕获异常是否是一个好主意。

i want to catch an exception like 'duplicate entry for 1-0' if so then handle exception otherwise insert properly in database table? 我想捕获一个异常,例如“ 1-0重复项”,然后处理异常,否则在数据库表中正确插入?

I say you don't do that, for two reasons: 我说你不这样做,有两个原因:

  • the error messages are a bit unclear: ERROR 1062 (23000): Duplicate entry 'xxx' for key 1 . 错误消息有点不清楚: 错误1062(23000):密钥1的条目“ xxx”重复 Are you always 100% sure which key is 1? 您是否总是100%确定哪个键是1?
  • it locks in you to a specific database vendor 它将您锁定到特定的数据库供应商

I find it simpler to transactionally : 我发现交易更简单:

  • check for row's existence; 检查行的存在;
  • throw an exception if the row already exists; 如果该行已经存在,则引发异常;
  • insert the new row. 插入新行。

Performance issues : 性能问题

I say measure twice, cut once . 我说测量两次,切一次 Profile the usage for your specific use case. 剖析您特定用例的用法。 Top of my head I would say that the performance will not be an issue except for the heavy db usage scenarios. 我要说的是,除了大量的数据库使用情况之外,性能将不是问题。

The reason is that once you perform a SELECT over that specific row, its data will be placed in the database caches and immediately used for insertion check done on the index for the INSERT statement. 原因是,一旦您在该特定行上执行了SELECT ,它的数据将被放置在数据库缓存中,并立即用于对INSERT语句的索引进行插入检查。 Also keeping in mind that this access is backed by an index leads to the conclusion that performance will not be an issue. 同样要记住,此访问由索引支持,因此得出结论,性能将不是问题。

But, as always, do measure. 但是,像往常一样,要进行测量。

I don't see why not. 我不明白为什么不这样。 It's probably more efficient than running a query before the insert. 它可能比在插入之前运行查询更有效。 It's probably better to catch the exception's error code rather than recognising the error message, though. 但是,捕获异常的错误代码可能比识别错误消息要好。

You could use the REPLACE command. 您可以使用REPLACE命令。 It inserts/updates based on the existence of the record. 它根据记录的存在来插入/更新。 And its atomic too whereas query then insert/update is not. 而且它也是原子的,而查询然后不是插入/更新。 It depends on what do you want to do if you detect the key violation? 如果检测到密钥冲突,这取决于您要做什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM