oracle 使用 JDBC 捕获和处理 ORA-00001 SQLException 的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5719284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 23:23:59  来源:igfitidea点击:

What is the proper way to catch and handle ORA-00001 SQLException with JDBC?

oraclejdbcprimary-keyconstraintsora-00001

提问by Luke

I'm creating a simple form that stores entered data in an extremely simple Oracle database table via a Java Servlet using JDBC. That table is using the email address as a primary key. If a user submits a form multiple times with the same email address, the executefunction fails and throws a SQLException. The exception's string is the following:

我正在创建一个简单的表单,它使用 JDBC 通过 Java Servlet 将输入的数据存储在一个非常简单的 Oracle 数据库表中。该表使用电子邮件地址作为主键。如果用户使用相同的电子邮件地址多次提交表单,该execute函数将失败并抛出 SQLException。异常的字符串如下:

java.sql.SQLException: ORA-00001: unique constraint (...removed...) violated

In this scenario, I would like to catch this exception and deal with it by telling the user that the form cannot be submitted multiple times with the same email address. What is the proper way to handle ORA-00001 separately and differently from any of the other SQLExceptions that can be thrown by execute? A string compare could obviously work here, but that seems like a poor solution.

在这种情况下,我想捕获此异常并通过告诉用户无法使用相同的电子邮件地址多次提交表单来处理它。分别处理 ORA-00001 的正确方法是什么execute?字符串比较显然可以在这里工作,但这似乎是一个糟糕的解决方案。

回答by a_horse_with_no_name

If you don't need to be DBMS independent use SQLException.getErrorCode()

如果你不需要被 DBMS 独立使用 SQLException.getErrorCode()

It returns the vendor specific numeric error code. For ORA-0001 this would be 1

它返回供应商特定的数字错误代码。对于 ORA-0001,这将是1