java 如何捕获数据的 SQLException?(例如。数据不存在)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5209284/
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
How to catch SQLException of Data ? (eg. Data not exist)
提问by 1myb
Searching Solution for this question for long period but still unmanaged to get a answer for this, I'm trying to make a search box in my application made with JAVA.
长时间搜索这个问题的解决方案但仍然无法得到答案,我正在尝试在我用 JAVA 制作的应用程序中创建一个搜索框。
I want to catch the exception from database and telling user that column doesn't exist or duplication data, may i know how could i do this ?
我想从数据库中捕获异常并告诉用户该列不存在或重复数据,我可以知道我该怎么做吗?
回答by klonq
This is not really an easy thing to do and the solution will depend a lot on the vendor of the SQL connection (ie, mySQL, oracle, etc)
这并不是一件容易的事情,解决方案在很大程度上取决于 SQL 连接的供应商(即 mySQL、oracle 等)
I have shown one way to do this using pattern matching of the SQLException error message
我已经展示了一种使用 SQLException 错误消息的模式匹配来做到这一点的方法
private final int INEXISTENT_COLUMN_ERROR = ?
private final int DUPLICATE_DATA_ERROR = ?
private final String INEXISTENT_COLUMN_PATTERN = ?;
private final String DUPLICATE_DATA_PATTERN = ?;
...
try {
...
} catch (SQLException e){
if (e.getErrorCode() == INEXISTENT_COLUMN_ERROR)
System.out.println("User friendly error message caused by column " + this.matchPattern(e.getMessage(), this.INEXISTENT_COLUMN_PATTERN));
if (e.getErrorCode() == DUPLICATE_DATA_ERROR)
System.out.println("User friendly error message caused by duplicate data " + this.matchPattern(e.getMessage(), this.DUPLICATE_DATA_PATTERN));
}
...
private String matchPattern(final String string, final String pattern) {
final Pattern p = Pattern.compile(pattern);
final Matcher m = p.matcher(string);
...
}