mysql唯一索引用作java中的异常处理方法 [英] mysql unique index used as exception handling method in java

查看:6353
本文介绍了mysql唯一索引用作java中的异常处理方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道基于java中唯一的sql索引捕获异常是否是一个好主意。

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

我想捕获像'重复条目一样的异常对于1-0'如果是这样然后处理异常,否则在数据库表中正确插入?

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:


  • 错误消息有点不清楚: ERROR 1062(23000):重复输入'xxx'表示关键1 。你总是100%确定哪个键是1?

  • 它会锁定你到特定的数据库供应商

  • 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 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.

原因是一旦你执行 SELECT 在该特定行上,其数据将被放置在数据库缓存中,立即用于对 INSERT的索引进行插入检查声明。还要记住,这种访问是由索引支持的,这导致结果表明性能不会成为问题。

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.

这篇关于mysql唯一索引用作java中的异常处理方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆