java.sql.SQLException.getSQLState()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(10.7k)|赞(0)|评价(0)|浏览(298)

本文整理了Java中java.sql.SQLException.getSQLState()方法的一些代码示例,展示了SQLException.getSQLState()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。SQLException.getSQLState()方法的具体详情如下:
包路径:java.sql.SQLException
类名称:SQLException
方法名:getSQLState

SQLException.getSQLState介绍

[英]Retrieves the SQLState description string for this SQLException object.
[中]

代码示例

代码示例来源:origin: spring-projects/spring-framework

/**
 * Constructor for UncategorizedSQLException.
 * @param task name of current task
 * @param sql the offending SQL statement
 * @param ex the root cause
 */
public UncategorizedSQLException(String task, @Nullable String sql, SQLException ex) {
  super(task + "; uncategorized SQLException" + (sql != null ? " for SQL [" + sql + "]" : "") +
      "; SQL state [" + ex.getSQLState() + "]; error code [" + ex.getErrorCode() + "]; " +
      ex.getMessage(), ex);
  this.sql = sql;
}

代码示例来源:origin: debezium/debezium

/**
 * Creates a new exception instance, wrapping the supplied SQLException with a custom message
 *
 * @param message the exception message, may not be null
 * @param e a {@link SQLException} instance, may not be null
 */
public JdbcConnectionException(String message, SQLException e) {
  super(message, e);
  this.sqlState = e.getSQLState();
  this.errorCode = e.getErrorCode();
}

代码示例来源:origin: apache/hive

public static boolean isDeadlock(DatabaseProduct dbProduct, SQLException e) {
 return e instanceof SQLTransactionRollbackException
   || ((dbProduct == MYSQL || dbProduct == POSTGRES || dbProduct == SQLSERVER)
     && "40001".equals(e.getSQLState()))
   || (dbProduct == POSTGRES && "40P01".equals(e.getSQLState()))
   || (dbProduct == ORACLE && (e.getMessage() != null && (e.getMessage().contains("deadlock detected")
     || e.getMessage().contains("can't serialize access for this transaction"))));
}

代码示例来源:origin: spring-projects/spring-framework

private void logTranslation(String task, @Nullable String sql, SQLException sqlEx, boolean custom) {
  if (logger.isDebugEnabled()) {
    String intro = custom ? "Custom translation of" : "Translating";
    logger.debug(intro + " SQLException with SQL state '" + sqlEx.getSQLState() +
        "', error code '" + sqlEx.getErrorCode() + "', message [" + sqlEx.getMessage() + "]" +
        (sql != null ? "; SQL was [" + sql + "]": "") + " for task [" + task + "]");
  }
}

代码示例来源:origin: SonarSource/sonarqube

/**
 * Logback does not log exceptions associated to {@link java.sql.SQLException#getNextException()}.
 * See http://jira.qos.ch/browse/LOGBACK-775
 */
public static void log(Logger logger, SQLException e) {
 SQLException next = e.getNextException();
 while (next != null) {
  logger.error("SQL error: {}. Message: {}", next.getSQLState(), next.getMessage());
  next = next.getNextException();
 }
}

代码示例来源:origin: alibaba/druid

@Override
public boolean isExceptionFatal(SQLException e) {
  if (e instanceof SQLRecoverableException) {
    return true;
  }
  String sqlState = e.getSQLState();
  if (sqlState != null && sqlState.startsWith("08")) { // Connection Exception
    return true;
  }
  int errorCode = e.getErrorCode();
  switch (errorCode) {
    case -512: // STATEMENT REFERENCE TO REMOTE OBJECT IS INVALID
    case -514: // THE CURSOR IS NOT IN A PREPARED STATE
    case -516: // THE DESCRIBE STATEMENT DOES NOT SPECIFY A PREPARED STATEMENT
    case -518: // THE EXECUTE STATEMENT DOES NOT IDENTIFY A VALID PREPARED STATEMENT
    case -525: // THE SQL STATEMENT CANNOT BE EXECUTED BECAUSE IT WAS IN ERROR AT BIND TIME FOR SECTION = sectno
          // PACKAGE = pkgname CONSISTENCY TOKEN = contoken
    case -909: // THE OBJECT HAS BEEN DELETED OR ALTERED
    case -918: // THE SQL STATEMENT CANNOT BE EXECUTED BECAUSE A CONNECTION HAS BEEN LOST
    case -924: // DB2 CONNECTION INTERNAL ERROR, function-code,return-code,reason-code
      return true;
    default:
      break;
  }
  return false;
}

代码示例来源:origin: apache/incubator-shardingsphere

public ErrPacket(final int sequenceId, final SQLException cause) {
  this(sequenceId, cause.getErrorCode(), cause.getSQLState(), cause.getMessage());
}

代码示例来源:origin: hibernate/hibernate-orm

/**
   * Extract the name of the violated constraint from the given SQLException.
   *
   * @param sqle The exception that was the result of the constraint violation.
   * @return The extracted constraint name.
   */
  @Override
  protected String doExtractConstraintName(SQLException sqle) throws NumberFormatException {
    String constraintName = null;
    // 23000: Check constraint violation: {0}
    // 23001: Unique index or primary key violation: {0}
    if ( sqle.getSQLState().startsWith( "23" ) ) {
      final String message = sqle.getMessage();
      final int idx = message.indexOf( "violation: " );
      if ( idx > 0 ) {
        constraintName = message.substring( idx + "violation: ".length() );
      }
    }
    return constraintName;
  }
};

代码示例来源:origin: AxonFramework/AxonFramework

/**
 * @param sqlException The exception to locate the error code in
 * @param errorCodes   The error codes indicating duplicate key violations
 * @return {@code true} if the error code of the {@code sqlException} is in the given list of {@code errorCodes}, otherwise
 * {@code false}
 */
protected boolean isDuplicateKeyCode(SQLException sqlException, List<Integer> errorCodes) {
  if (errorCodes.contains(sqlException.getErrorCode())) {
    return true;
  } else if (sqlException.getSQLState() != null) {
    try {
      return errorCodes.contains(Integer.parseInt(sqlException.getSQLState()));
    } catch (NumberFormatException e) {
      return false;
    }
  }
  return false;
}

代码示例来源:origin: apache/incubator-shardingsphere

public ErrPacket(final int sequenceId, final SQLException cause) {
  this(sequenceId, cause.getErrorCode(), cause.getSQLState(), cause.getMessage());
}

代码示例来源:origin: com.zaxxer/HikariCP

/**
* Check the default transaction isolation of the Connection.
*
* @param connection a Connection to check
* @throws SQLException rethrown from the driver
*/
private void checkDefaultIsolation(final Connection connection) throws SQLException
{
 try {
   defaultTransactionIsolation = connection.getTransactionIsolation();
   if (transactionIsolation == -1) {
    transactionIsolation = defaultTransactionIsolation;
   }
 }
 catch (SQLException e) {
   logger.warn("{} - Default transaction isolation level detection failed ({}).", poolName, e.getMessage());
   if (e.getSQLState() != null && !e.getSQLState().startsWith("08")) {
    throw e;
   }
 }
}

代码示例来源:origin: apache/hive

private boolean isDuplicateKeyError(SQLException ex) {
 switch (dbProduct) {
  case DERBY:
   if("23505".equals(ex.getSQLState())) {
    return true;
  case MYSQL:
   if((ex.getErrorCode() == 1022 || ex.getErrorCode() == 1062 || ex.getErrorCode() == 1586)
    && "23000".equals(ex.getSQLState())) {
    return true;
  case SQLSERVER:
   if(ex.getErrorCode() == 2627 && "23000".equals(ex.getSQLState())) {
    return true;
   if(ex.getErrorCode() == 1 && "23000".equals(ex.getSQLState())) {
    return true;
  case POSTGRES:
   if("23505".equals(ex.getSQLState())) {
    return true;

代码示例来源:origin: apache/hive

private static String getMessage(SQLException ex) {
 return ex.getMessage() + " (SQLState=" + ex.getSQLState() + ", ErrorCode=" + ex.getErrorCode() + ")";
}
/**

代码示例来源:origin: apache/hive

/**
 * Returns true if {@code ex} should be retried
 */
static boolean isRetryable(Configuration conf, Exception ex) {
 if(ex instanceof SQLException) {
  SQLException sqlException = (SQLException)ex;
  if("08S01".equalsIgnoreCase(sqlException.getSQLState())) {
   //in MSSQL this means Communication Link Failure
   return true;
  }
  if("ORA-08176".equalsIgnoreCase(sqlException.getSQLState()) ||
   sqlException.getMessage().contains("consistent read failure; rollback data not available")) {
   return true;
  }
  String regex = MetastoreConf.getVar(conf, ConfVars.TXN_RETRYABLE_SQLEX_REGEX);
  if (regex != null && !regex.isEmpty()) {
   String[] patterns = regex.split(",(?=\\S)");
   String message = getMessage((SQLException)ex);
   for (String p : patterns) {
    if (Pattern.matches(p, message)) {
     return true;
    }
   }
  }
  //see also https://issues.apache.org/jira/browse/HIVE-9938
 }
 return false;
}
private boolean isDuplicateKeyError(SQLException ex) {

代码示例来源:origin: apache/ignite

/**
 * @param e Exception to write.
 * @param gen JSON generator.
 * @throws IOException If failed to write.
 */
private void writeException(Throwable e, JsonGenerator gen) throws IOException {
  if (e instanceof VisorExceptionWrapper) {
    VisorExceptionWrapper wrapper = (VisorExceptionWrapper)e;
    gen.writeStringField("className", wrapper.getClassName());
  }
  else
    gen.writeStringField("className", e.getClass().getName());
  if (e.getMessage() != null)
    gen.writeStringField("message", e.getMessage());
  if (e instanceof SQLException) {
    SQLException sqlE = (SQLException)e;
    gen.writeNumberField("errorCode", sqlE.getErrorCode());
    gen.writeStringField("SQLState", sqlE.getSQLState());
  }
}

代码示例来源:origin: com.h2database/h2

private static SQLClientInfoException convertToClientInfoException(
    SQLException x) {
  if (x instanceof SQLClientInfoException) {
    return (SQLClientInfoException) x;
  }
  return new SQLClientInfoException(x.getMessage(), x.getSQLState(),
      x.getErrorCode(), null, null);
}

代码示例来源:origin: alibaba/druid

} catch (SQLException e) {
      if ("Method not supported".equals(e.getMessage())) {
        holdabilityUnsupported = true;
} catch (SQLException e) {
  if ("HY000".equals(e.getSQLState())
      || "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException".equals(e.getClass().getName())) {

代码示例来源:origin: killbill/killbill

private void errorDuringTransaction(final Throwable t, final Method method, final String extraErrorMessage) throws Throwable {
  final StringBuilder errorMessageBuilder = new StringBuilder("Error during transaction for sql entity {} and method {}");
  if (t instanceof SQLException) {
    final SQLException sqlException = (SQLException) t;
    errorMessageBuilder.append(" [SQL DefaultState: ")
              .append(sqlException.getSQLState())
              .append(", Vendor Error Code: ")
              .append(sqlException.getErrorCode())
              .append("]");
  }
  if (extraErrorMessage != null) {
    // This is usually the SQL statement
    errorMessageBuilder.append("\n").append(extraErrorMessage);
  }
  logger.warn(errorMessageBuilder.toString(), sqlDaoClass, method.getName());
  // This is to avoid throwing an exception wrapped in an UndeclaredThrowableException
  if (!(t instanceof RuntimeException)) {
    throw new RuntimeException(t);
  } else {
    throw t;
  }
}

代码示例来源:origin: com.h2database/h2

/**
 * INTERNAL
 */
JdbcBatchUpdateException(SQLException next, int[] updateCounts) {
  super(next.getMessage(), next.getSQLState(), next.getErrorCode(), updateCounts);
  setNextException(next);
}

代码示例来源:origin: apache/hive

public static ExecuteStatementOperation newExecuteStatementOperation(HiveSession parentSession,
   String statement, Map<String, String> confOverlay, boolean runAsync, long queryTimeout)
   throws HiveSQLException {

  String cleanStatement = HiveStringUtils.removeComments(statement);
  String[] tokens = cleanStatement.trim().split("\\s+");
  CommandProcessor processor = null;
  try {
   processor = CommandProcessorFactory.getForHiveCommand(tokens, parentSession.getHiveConf());
  } catch (SQLException e) {
   throw new HiveSQLException(e.getMessage(), e.getSQLState(), e);
  }
  if (processor == null) {
   // runAsync, queryTimeout makes sense only for a SQLOperation
   // Pass the original statement to SQLOperation as sql parser can remove comments by itself
   return new SQLOperation(parentSession, statement, confOverlay, runAsync, queryTimeout);
  }
  return new HiveCommandOperation(parentSession, cleanStatement, processor, confOverlay);
 }
}

相关文章