Java Utililty Methods SQLException

List of utility methods to do SQLException

Description

The list of methods to do SQLException are organized into topic(s).

Method

StringgetSQLExceptionMessage(SQLException ex)
get SQL Exception Message
return String.format("SQL Code: %s Message: %s", ex.getErrorCode(), ex.getMessage());
StringBuildergetSqlStateString(SQLException se)
get Sql State String
StringBuilder result = new StringBuilder(30);
try {
    String state = se.getSQLState();
    if (state != null && state.length() > 0) {
        result.append("SQL State=");
        result.append(state);
    int error = se.getErrorCode();
...
StringgetStringFromException(java.lang.Throwable exception)
Gets a String message from an Exception.
StringBuilder msg = new StringBuilder();
if (exception != null) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    exception.printStackTrace(printWriter);
    printWriter.close();
    try {
        stringWriter.close();
...
booleanisConnectionError(final SQLException error)
Checks if an SQLException is a connection error.

A connection error can be caused by network errors.

int errorCode = error.getErrorCode();
if (errorCode == 17002) {
    return true;
} else {
    return false;
booleanisConstraintViolation(SQLException e)
is Constraint Violation
return e.getSQLState().startsWith("23");
booleanisDatabaseAlreadyExistsException(Exception e)
Indicates whether an exception is a result of a particular database already existing in the MySQL instance.
return e instanceof SQLException && ((SQLException) e).getErrorCode() == MYSQL_DB_ALREADY_EXISTS_ERROR_CODE;
booleanisDataConversionException(SQLException se)
is Data Conversion Exception
if ((se.getMessage() != null && se.getMessage().indexOf("Invalid data conversion") >= 0)
        || (se.getSQLState() != null && (se.getSQLState().equals("22018")
                || se.getSQLState().equals("22005") || se.getSQLState().equals("22007"))))
    return true;
return false;
booleanisDuplicateKeyException(Exception ex)
Returns true if the given exception is because of a duplicate key error
if (ex instanceof SQLIntegrityConstraintViolationException) {
    return (true);
} else if (ex instanceof SQLException) {
    SQLException sqlEx = (SQLException) ex;
    if (sqlEx.getSQLState().contains("23505")) {
        return (true);
return (false);
booleanisInvalidParameterException(SQLException se)
is Invalid Parameter Exception
if ((se.getMessage() != null && se.getMessage().indexOf("Invalid parameter value") >= 0)
        || (se.getMessage().indexOf("Invalid fetch size") >= 0)
        || (se.getMessage().indexOf("Invalid fetch direction") >= 0)
        || (se.getSQLState() != null && (se.getSQLState().equals("XJ066"))))
    return true;
return false;
booleanisPSQLUniqueViolation(SQLException ex)
Is the specified exception a PostgreSQL unique violation.
return "23505".equals(Objects.requireNonNull(ex).getSQLState());