5

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 ?

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1myb
  • 3,536
  • 12
  • 53
  • 73

1 Answers1

6

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);
    ...
}
klonq
  • 3,535
  • 4
  • 36
  • 58
  • Thx for your example and that's what i want, may i know is there a list of DUPLICATE DATA ERROR...or other sql error code ? my primary database is MSSql. Thank you =D – 1myb Mar 06 '11 at 14:03
  • @spencer you should have a look on google for a list of error codes from your vendor. but you could also figure them out for your self System.out.print(e.getErrorCode()) – klonq Mar 06 '11 at 23:54
  • Thx =D failed to do in java because using eclipse, weak in debug but work in c# (visual studio) ^^ – 1myb Mar 07 '11 at 03:48