开发者

How to catch SQLException of Data ? (eg. Data not exist)

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.

I want to cat开发者_如何学编程ch the exception from database and telling user that column doesn't exist or duplication data, may i know how could i do this ?


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)

I have shown one way to do this using pattern matching of the SQLException error message

    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);
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜