Show SQL error message

2019-02-20 18:25发布

问题:

I am using JDBC to connect to MySQL in my java project. I have implemented some check constraints in the mySQL table.

I have a form in which the user enters some values and submits it to the MySQL table. If a constraint is violated, Java gives an SQLException.

My aim is to display as a popup message as to which condition was violated in my table.

How do I retreive this information in java?

I tried a logger, but it only shows a lengthy error message in console.

回答1:

You can check out this:-

public static void printSQLException(SQLException ex) {

    for (Throwable e : ex) {
        if (e instanceof SQLException) {
            if (ignoreSQLException(
                ((SQLException)e).
                getSQLState()) == false) {

                e.printStackTrace(System.err);
                System.err.println("SQLState: " +
                    ((SQLException)e).getSQLState());

                System.err.println("Error Code: " +
                    ((SQLException)e).getErrorCode());

                System.err.println("Message: " + e.getMessage());

                Throwable t = ex.getCause();
                while(t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
}