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

1myb picture 1myb · Mar 6, 2011 · Viewed 22.2k times · Source

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 catch the exception from database and telling user that column doesn't exist or duplication data, may i know how could i do this ?

Answer

klonq picture klonq · Mar 6, 2011

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