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

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

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

SQLException.getErrorCode介绍

[英]Returns the integer error code for this SQLException.
[中]返回此SQLException的整数错误代码。

代码示例

代码示例来源: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/activemq

private void executeStatement(TransactionContext transactionContext, String createStatement, boolean ignoreStatementExecutionFailure) throws IOException {
  Statement statement = null;
  try {
    LOG.debug("Executing SQL: " + createStatement);
    statement = transactionContext.getConnection().createStatement();
    statement.execute(createStatement);
    commitIfAutoCommitIsDisabled(transactionContext);
  } catch (SQLException e) {
    if (ignoreStatementExecutionFailure) {
      LOG.debug("Could not create JDBC tables; The message table already existed. " + String.format(FAILURE_MESSAGE, createStatement, e.getMessage(), e.getSQLState(), e.getErrorCode()));
    } else {
      LOG.warn("Could not create JDBC tables; they could already exist. " + String.format(FAILURE_MESSAGE, createStatement, e.getMessage(), e.getSQLState(), e.getErrorCode()));
      JDBCPersistenceAdapter.log("Failure details: ", e);
    }
  } finally {
    closeStatement(statement);
  }
}

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

@Test
public void testInvalidArrayElemRefInUpsert() throws Exception {
  Connection conn = DriverManager.getConnection(getUrl());
  conn.createStatement().execute("CREATE TABLE t (k VARCHAR PRIMARY KEY, a INTEGER[10], B INTEGER[10])");
  try {
    conn.createStatement().execute("UPSERT INTO t(k,a[2]) VALUES('A', 5)");
    fail();
  } catch (SQLException e) {
    assertEquals(SQLExceptionCode.PARSER_ERROR.getErrorCode(), e.getErrorCode());
  }
  conn.close();
}

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

@Test
public void testEventuallyFails() {
  final AtomicInteger attempts = new AtomicInteger(0);
  Handle handle = dbRule.getJdbi().open();
  assertThatExceptionOfType(SQLException.class)
    .isThrownBy(() -> handle.inTransaction(TransactionIsolationLevel.SERIALIZABLE,
      conn -> {
        attempts.incrementAndGet();
        throw new SQLException("serialization", "40001", attempts.get());
      }))
    .satisfies(e -> assertThat(e.getSQLState()).isEqualTo("40001"))
    .satisfies(e -> assertThat(e.getSuppressed())
      .hasSize(MAX_RETRIES)
      .describedAs("suppressed are ordered reverse chronologically, like a stack")
      .isSortedAccordingTo(Comparator.comparing(ex -> ((SQLException) ex).getErrorCode()).reversed()))
    .describedAs("thrown exception is chronologically last")
    .satisfies(e -> assertThat(e.getErrorCode()).isEqualTo(((SQLException) e.getSuppressed()[0]).getErrorCode() + 1));
  assertThat(attempts.get()).isEqualTo(1 + MAX_RETRIES);
}

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

@Test
public void testVersionMismatchJdbc() throws Exception {
  try (Connection conn1 = connect(); Connection conn2 = connect()) {
      assertEquals(SqlStateCode.SERIALIZATION_FAILURE, e.getSQLState());
      assertEquals(IgniteQueryErrorCode.TRANSACTION_SERIALIZATION_ERROR, e.getErrorCode());
      assertNotNull(e.getMessage());
      assertTrue(e.getMessage().contains("Cannot serialize transaction due to write conflict"));
      assertEquals(SqlStateCode.TRANSACTION_STATE_EXCEPTION, e.getSQLState());
      assertEquals(IgniteQueryErrorCode.TRANSACTION_COMPLETED, e.getErrorCode());
      assertNotNull(e.getMessage());
      assertTrue(e.getMessage().contains("Transaction is already completed"));
      assertEquals(SqlStateCode.INTERNAL_ERROR, e.getSQLState());
      assertEquals(IgniteQueryErrorCode.UNKNOWN, e.getErrorCode());
      assertNotNull(e.getMessage());

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

@Test
public void testFailureAndSuccessCallback() throws SQLException {
  AtomicInteger remainingAttempts = new AtomicInteger(MAX_RETRIES);
      .hasSize(expectedExceptions.getAndIncrement())
      .describedAs("ordered chronologically")
      .isSortedAccordingTo(Comparator.comparing(e -> ((SQLException) e).getErrorCode()));
    return null;
  }).when(onFailure).accept(anyList());
      .hasSize(MAX_RETRIES - 1)
      .describedAs("ordered chronologically")
      .isSortedAccordingTo(Comparator.comparing(e -> ((SQLException) e).getErrorCode()));
    return null;
  }).when(onSuccess).accept(anyList());

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

@Test
public void testVarbinaryArrayNotSupported() throws Exception {
  Connection conn = DriverManager.getConnection(getUrl());
  try {
    conn.createStatement().execute("CREATE TABLE t (k VARCHAR PRIMARY KEY, a VARBINARY[10])");
    fail();
  } catch (SQLException e) {
    assertEquals(SQLExceptionCode.VARBINARY_ARRAY_NOT_SUPPORTED.getErrorCode(), e.getErrorCode());
  }
  conn.close();
}

代码示例来源: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: apache/activemq

@Override
public void doDropTables(TransactionContext c) throws SQLException, IOException {
  Statement s = null;
  try {
    s = c.getConnection().createStatement();
    String[] dropStatments = this.statements.getDropSchemaStatements();
    for (int i = 0; i < dropStatments.length; i++) {
      // This will fail usually since the tables will be
      // created already.
      try {
        LOG.debug("Executing SQL: " + dropStatments[i]);
        s.execute(dropStatments[i]);
      } catch (SQLException e) {
        LOG.warn("Could not drop JDBC tables; they may not exist." + " Failure was: " + dropStatments[i]
            + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: "
            + e.getErrorCode());
        JDBCPersistenceAdapter.log("Failure details: ", e);
      }
    }
    commitIfAutoCommitIsDisabled(c);
  } finally {
    try {
      s.close();
    } catch (Throwable e) {
    }
  }
}

代码示例来源: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/phoenix

@Test
public void testMutationUsingExecuteQueryShouldFail() throws Exception {
  Properties connectionProperties = new Properties();
  Connection connection = DriverManager.getConnection(getUrl(), connectionProperties);
  PreparedStatement stmt = connection.prepareStatement("DELETE FROM " + ATABLE);
  try {
    stmt.executeQuery();
    fail();
  } catch(SQLException e) {
    assertEquals(SQLExceptionCode.EXECUTE_QUERY_NOT_APPLICABLE.getErrorCode(), e.getErrorCode());
  }
}

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

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

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

@Override
public void preStart() {
  if (createTablesOnStartup) {
    String[] createStatements = getStatements().getCreateLockSchemaStatements();
    Connection connection = null;
    Statement statement = null;
    try {
      connection = getConnection();
      statement = connection.createStatement();
      setQueryTimeout(statement);
      for (int i = 0; i < createStatements.length; i++) {
        LOG.debug("Executing SQL: " + createStatements[i]);
        try {
          statement.execute(createStatements[i]);
        } catch (SQLException e) {
          LOG.info("Could not create lock tables; they could already exist." + " Failure was: "
              + createStatements[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState()
              + " Vendor code: " + e.getErrorCode());
        }
      }
    } catch (SQLException e) {
      LOG.warn("Could not create lock tables; Failure Message: " + e.getMessage() + " SQLState: " + e.getSQLState()
          + " Vendor code: " + e.getErrorCode(), e);
    } finally {
      close(statement);
      close(connection);
    }
  }
}

代码示例来源: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/phoenix

@Test
public void testQueriesUsingExecuteUpdateShouldFail() throws Exception {
  Properties connectionProperties = new Properties();
  Connection connection = DriverManager.getConnection(getUrl(), connectionProperties);
  PreparedStatement stmt = connection.prepareStatement("SELECT * FROM " + ATABLE);
  try {
    stmt.executeUpdate();
    fail();
  } catch(SQLException e) {
    assertEquals(SQLExceptionCode.EXECUTE_UPDATE_NOT_APPLICABLE.getErrorCode(), e.getErrorCode());
  }
}

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

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

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

try {
 conn = getConnection(conf);
 stmt = conn.createStatement();
  stmt.execute("DROP INDEX HL_TXNID_INDEX");
 } catch (SQLException e) {
  if(!("42X65".equals(e.getSQLState()) && 30000 == e.getErrorCode())) {
   LOG.error("Unable to drop index HL_TXNID_INDEX " + e.getMessage() +
    "State=" + e.getSQLState() + " code=" + e.getErrorCode() + " retryCount=" + retryCount);
   success = false;

代码示例来源: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: apache/phoenix

@Test
public void testArrayConcatSingleArg() throws SQLException {
  Connection conn = DriverManager.getConnection(getUrl());
  try {
    conn.createStatement().execute("CREATE TABLE t (p INTEGER PRIMARY KEY, arr1 INTEGER ARRAY, arr2 INTEGER ARRAY)");
    conn.createStatement().executeQuery("SELECT ARRAY_CAT(arr2) from t");
    fail();
  } catch (SQLException e) {
    assertEquals(SQLExceptionCode.FUNCTION_UNDEFINED.getErrorCode(),e.getErrorCode());
  } finally {
    conn.close();
  }
}

相关文章