Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 787
1myb Avatar asked Mar 06 '11 07:03

1myb


People also ask

Does exception catch SQLException?

SQLException is a specialized exception derived from Exception . If you catch Exception , all exception shall get caught. Even undesirable exceptions.

Is SQLException checked or unchecked?

1) Checked Exception The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.


1 Answers

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);
    ...
}
like image 53
klonq Avatar answered Sep 30 '22 13:09

klonq