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

bd96500e110b49cbb3cd949968f18be7.png

I want to know whether is it a good idea to catch exception based on unique index of sql in java.

i want to catch an exception like 'duplicate entry for 1-0' if so then handle exception otherwise insert properly in database table?

解决方案

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. Are you always 100% sure which key is 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. 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值