当前位置: 首页>>代码示例>>Java>>正文


Java SQLException.getSQLState方法代码示例

本文整理汇总了Java中java.sql.SQLException.getSQLState方法的典型用法代码示例。如果您正苦于以下问题:Java SQLException.getSQLState方法的具体用法?Java SQLException.getSQLState怎么用?Java SQLException.getSQLState使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.sql.SQLException的用法示例。


在下文中一共展示了SQLException.getSQLState方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: test

import java.sql.SQLException; //导入方法依赖的package包/类
protected boolean test(Statement aStatement) {

        try {
            aStatement.execute(getSql());
        } catch (SQLException sqlX) {
            caught = sqlX;

            if (expectedState == null
                    || expectedState.equalsIgnoreCase(sqlX.getSQLState())) {
                return true;
            }

            message = "SQLState '" + sqlX.getSQLState() + "' : "
                      + sqlX.toString() + " instead of '" + expectedState
                      + "'";
        } catch (Exception x) {
            caught  = x;
            message = x.toString();
        }

        return false;
    }
 
开发者ID:tiweGH,项目名称:OpenDiabetes,代码行数:23,代码来源:TestUtil.java

示例2: executeSQLUpdate

import java.sql.SQLException; //导入方法依赖的package包/类
/**
 * Executes a given SQL Statement.
 * @param stmt_text
 * @return the corresponding Result Set.
 * @throws SQLException 
 */
private void executeSQLUpdate(String stmt_text) throws SQLException{
    PreparedStatement stmt = conn.prepareStatement(stmt_text);
    
    try {
        stmt.executeUpdate();
    } catch(SQLException ex) {
        // If the system thinks we're missing a prepared statement, then we
        // should regenerate them.
        if (ex.getErrorCode() == 0 && ex.getSQLState() != null && ex.getSQLState().equals("07003")){
            stmt.executeUpdate();
        }
        else {
            throw ex;
        }    
    }
}
 
开发者ID:faclc4,项目名称:HTAPBench,代码行数:23,代码来源:ClientBalancer.java

示例3: canHandleFailure

import java.sql.SQLException; //导入方法依赖的package包/类
/**
 * Handle only connection reset or TCP exceptions.
 */
public boolean canHandleFailure(Throwable failureCause) {
  if (!super.canHandleFailure(failureCause)) {
    return false;
  }
  SQLException sqlEx = (SQLException) failureCause;
  String errStateCode = sqlEx.getSQLState();
  boolean canHandle = false;
  // By default check SQLState code if available
  if (errStateCode != null) {
    canHandle = errStateCode == SQLSTATE_CODE_CONNECTION_RESET;
  } else {
    errStateCode = "NULL";
    // In case SQLState code is not available, check the exception message
    String errMsg = sqlEx.getMessage();
    canHandle = errMsg.matches(CONNECTION_RESET_ERR_REGEX);
  }

  if (!canHandle) {
    LOG.warn("Cannot handle error with SQL State: " + errStateCode);
  }
  return canHandle;
}
 
开发者ID:aliyun,项目名称:aliyun-maxcompute-data-collectors,代码行数:26,代码来源:SQLServerConnectionFailureHandler.java

示例4: execute

import java.sql.SQLException; //导入方法依赖的package包/类
private void execute()
{
	m_sqlStatus.reset();
	try
	{
		if(m_preparedCallableStatement != null)
		{
			boolean b = m_preparedCallableStatement.execute();
		}
	}
	catch(SQLException e)
	{
		//String cs = e.getCause();
		String csState = e.getSQLState();
		String csReason = e.getMessage();
		Log.logImportant("Catched SQLException from stored procedure: "+csReason + " State="+csState);
		String csSPName = "StoredProc:" + m_csStoredProcName;
		m_sqlStatus.setSQLCode(csSPName, e.getErrorCode(), csReason, csState);
	}
}
 
开发者ID:costea7,项目名称:ChronoBike,代码行数:21,代码来源:SQLCall.java

示例5: setClientInfo

import java.sql.SQLException; //导入方法依赖的package包/类
public void setClientInfo(String name,
                          String value) throws SQLClientInfoException {

    try {
        validate();
    } catch (SQLException e) {
        throw new SQLClientInfoException(e.getMessage(), e.getSQLState(),
                e.getErrorCode(), (Map<String, ClientInfoStatus>) null, e);
    }
    this.getConnection().setClientInfo(name, value);
}
 
开发者ID:s-store,项目名称:sstore-soft,代码行数:12,代码来源:BaseConnectionWrapper.java

示例6: run

import java.sql.SQLException; //导入方法依赖的package包/类
public int run(Connection conn,Clock clock, WorkloadConfiguration wrklConf) throws SQLException {
    //initializing all prepared statements
    stmt = this.getPreparedStatement(conn, get_query(clock,wrklConf));
    
    LOG.debug("Query SQL STMT:"+ get_query(clock,wrklConf).getSQL());
    
    if (owner != null)
        owner.setCurrStatement(stmt);

    //LOG.debug(this.getClass());
    LOG.info(this.getClass());
    ResultSet rs = null;
    try {            
        rs = stmt.executeQuery();
    } catch(SQLException ex) {
        // If the system thinks we're missing a prepared statement, then we
        // should regenerate them.
        if (ex.getErrorCode() == 0 && ex.getSQLState() != null
            && ex.getSQLState().equals("07003"))
        {
            this.resetPreparedStatements();
            rs = stmt.executeQuery();
        }
        else {
            throw ex;
        }
    }
    int t = 0;
    while (rs.next()) {
        t = t+1;
    }

    if (owner != null)
        owner.setCurrStatement(null);
    
    return t;

}
 
开发者ID:faclc4,项目名称:HTAPBench,代码行数:39,代码来源:GenericQuery.java

示例7: extractSqlState

import java.sql.SQLException; //导入方法依赖的package包/类
/**
 * Helper method to extract state of SQL exception.
 *
 * @param sqlException the SQL exception thrown
 * @return the SQL state of the exception
 */
private String extractSqlState(SQLException sqlException) {
    String sqlState = sqlException.getSQLState();
    SQLException nextException = sqlException.getNextException();
    while (sqlState == null && nextException != null) {
        sqlState = nextException.getSQLState();
        nextException = nextException.getNextException();
    }
    return sqlState;
}
 
开发者ID:wso2,项目名称:message-broker,代码行数:16,代码来源:RdbmsCoordinationDaoImpl.java

示例8: shouldExceptionTriggerFailover

import java.sql.SQLException; //导入方法依赖的package包/类
public boolean shouldExceptionTriggerFailover(SQLException ex) {
    String sqlState = ex.getSQLState();

    if (sqlState != null) {
        if (sqlState.startsWith("08")) {
            // connection error
            return true;
        }
        if (this.sqlStateList != null) {
            // check against SQLState list
            for (Iterator<String> i = this.sqlStateList.iterator(); i.hasNext();) {
                if (sqlState.startsWith(i.next().toString())) {
                    return true;
                }
            }
        }
    }

    // always handle CommunicationException
    if (ex instanceof CommunicationsException) {
        return true;
    }

    if (this.sqlExClassList != null) {
        // check against configured class lists
        for (Iterator<Class<?>> i = this.sqlExClassList.iterator(); i.hasNext();) {
            if (i.next().isInstance(ex)) {
                return true;
            }
        }
    }
    // no matches
    return false;
}
 
开发者ID:rafallis,项目名称:BibliotecaPS,代码行数:35,代码来源:StandardLoadBalanceExceptionChecker.java

示例9: isExceptionFatal

import java.sql.SQLException; //导入方法依赖的package包/类
@Override
public boolean isExceptionFatal(SQLException ex) {
    String sqlState = ex.getSQLState();

    if (sqlState != null && sqlState.startsWith("08")) {
        return true;
    }

    return super.isExceptionFatal(ex);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:11,代码来源:ExtendedMysqlExceptionSorter.java

示例10: execute

import java.sql.SQLException; //导入方法依赖的package包/类
/**
 * Adjust this method for large strings...ie multi megabtypes.
 */
void execute() {

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
        sCmd = ifHuge;
    } else {
        sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
        testPerformance();

        return;
    }

    String[] g = new String[1];

    lTime = System.currentTimeMillis();

    try {
        if (sStatement == null) {
            return;
        }

        sStatement.execute(sCmd);

        lTime = System.currentTimeMillis() - lTime;

        int r = sStatement.getUpdateCount();

        if (r == -1) {
            formatResultSet(sStatement.getResultSet());
        } else {
            g[0] = "update count";

            gResult.setHead(g);

            g[0] = String.valueOf(r);

            gResult.addRow(g);
        }

        addToRecent(txtCommand.getText());
    } catch (SQLException e) {
        lTime = System.currentTimeMillis() - lTime;
        g[0]  = "SQL Error";

        gResult.setHead(g);

        String s = e.getMessage();

        s    += " / Error Code: " + e.getErrorCode();
        s    += " / State: " + e.getSQLState();
        g[0] = s;

        gResult.addRow(g);
    }

    updateResult();
    System.gc();
}
 
开发者ID:s-store,项目名称:sstore-soft,代码行数:66,代码来源:DatabaseManager.java

示例11: write

import java.sql.SQLException; //导入方法依赖的package包/类
/**
 * Write the records to the database. If a failure occurs, it tries to
 * use the configured handler to recover from the failure, otherwise
 * a SQLException is throw
 */
protected void write(List<SqoopRecord> records)
    throws SQLException, IOException {
  PreparedStatement stmt = null;
  int retryCount = RETRY_MAX;
  boolean doRetry = true;

  do {
    try {
      // Establish the connection to be used if not yet created
      getConnection();

      // Get the prepared statement to use for writing the records
      stmt = getPreparedStatement(records);

      // Execute the prepared statement
      executeStatement(stmt, records);

      // Statement executed successfully, no need to retry
      doRetry = false;
    } catch (SQLException sqlEx) {
      LOG.warn("Trying to recover from DB write failure: ", sqlEx);

      // Use configured connection handler to recover from the connection
      // failure and use the recovered connection.
      // If the failure cannot be recovered, an exception is thrown
      if (failureHandler.canHandleFailure(sqlEx)) {
        // Recover from connection failure
        this.conn = failureHandler.recover();

        // Configure the new connection before using it
        configureConnection();

        --retryCount;
        doRetry = (retryCount >= 0);
      } else {
        // Cannot recover using configured handler, re-throw
        throw new IOException("Registered handler cannot recover error "
          + "with SQL State: " + sqlEx.getSQLState() + ", error code: "
          + sqlEx.getErrorCode(), sqlEx);
      }
    }
  } while (doRetry);

  // Throw an exception if all retry attempts are consumed
  if (retryCount < 0) {
    throw new IOException("Failed to write to database after "
      + RETRY_MAX + " retries.");
  }
}
 
开发者ID:aliyun,项目名称:aliyun-maxcompute-data-collectors,代码行数:55,代码来源:SQLServerAsyncDBExecThread.java

示例12: appendMessageToException

import java.sql.SQLException; //导入方法依赖的package包/类
protected static SQLException appendMessageToException(SQLException sqlEx, String messageToAppend, ExceptionInterceptor interceptor) {
    String origMessage = sqlEx.getMessage();
    String sqlState = sqlEx.getSQLState();
    int vendorErrorCode = sqlEx.getErrorCode();

    StringBuilder messageBuf = new StringBuilder(origMessage.length() + messageToAppend.length());
    messageBuf.append(origMessage);
    messageBuf.append(messageToAppend);

    SQLException sqlExceptionWithNewMessage = SQLError.createSQLException(messageBuf.toString(), sqlState, vendorErrorCode, interceptor);

    //
    // Try and maintain the original stack trace, only works on JDK-1.4 and newer
    //

    try {
        // Have to do this with reflection, otherwise older JVMs croak
        Method getStackTraceMethod = null;
        Method setStackTraceMethod = null;
        Object theStackTraceAsObject = null;

        Class<?> stackTraceElementClass = Class.forName("java.lang.StackTraceElement");
        Class<?> stackTraceElementArrayClass = Array.newInstance(stackTraceElementClass, new int[] { 0 }).getClass();

        getStackTraceMethod = Throwable.class.getMethod("getStackTrace", new Class[] {});

        setStackTraceMethod = Throwable.class.getMethod("setStackTrace", new Class[] { stackTraceElementArrayClass });

        if (getStackTraceMethod != null && setStackTraceMethod != null) {
            theStackTraceAsObject = getStackTraceMethod.invoke(sqlEx, new Object[0]);
            setStackTraceMethod.invoke(sqlExceptionWithNewMessage, new Object[] { theStackTraceAsObject });
        }
    } catch (NoClassDefFoundError noClassDefFound) {

    } catch (NoSuchMethodException noSuchMethodEx) {

    } catch (Throwable catchAll) {

    }

    return sqlExceptionWithNewMessage;
}
 
开发者ID:rafallis,项目名称:BibliotecaPS,代码行数:43,代码来源:ConnectionImpl.java

示例13: GokuSQLException

import java.sql.SQLException; //导入方法依赖的package包/类
public GokuSQLException(SQLException orig) {
    super(orig.getMessage(), orig.getSQLState(), orig.getErrorCode(), orig);
}
 
开发者ID:kawasima,项目名称:goku-jdbc,代码行数:4,代码来源:GokuSQLException.java

示例14: executeSQL

import java.sql.SQLException; //导入方法依赖的package包/类
private void executeSQL() {

        String[] g   = new String[1];
        String   sql = null;

        try {
            lTime = System.currentTimeMillis();
            sql   = ((sqlScriptBuffer == null ? txtCommand.getText()
                                              : sqlScriptBuffer));

            sStatement.execute(sql);

            int r = sStatement.getUpdateCount();

            if (r == -1) {
                formatResultSet(sStatement.getResultSet());
            } else {
                g[0] = "update count";

                gResult.setHead(g);

                g[0] = "" + r;

                gResult.addRow(g);
            }

            lTime = System.currentTimeMillis() - lTime;

            if (sqlScriptBuffer == null) {
                addToRecent(sql);
                txtCommand.setEnabled(true);    // clear() does this otherwise
            } else {
                clear();
            }
        } catch (SQLException e) {
            lTime = System.currentTimeMillis() - lTime;
            g[0]  = "SQL Error";

            gResult.setHead(g);

            String s = e.getMessage();

            s    += " / Error Code: " + e.getErrorCode();
            s    += " / State: " + e.getSQLState();
            g[0] = s;

            gResult.addRow(g);

            //  Added: ([email protected])
            CommonSwing.errorMessage(e);

            return;
        }

        if (autoRefresh) {

            // We're already running in a "busy" thread.  Just update the
            // status text.
            setStatusLine("Refreshing object tree", 0);

            String upper = sql.toUpperCase(Locale.ENGLISH);

            // This test can be very liberal.  Too liberal will just do
            // some extra refreshes.  Too conservative will display
            // obsolete info.
            if (upper.indexOf("ALTER") > -1 || upper.indexOf("DROP") > -1
                    || upper.indexOf("CREATE") > -1) {
                directRefreshTree();
            }
        }
    }
 
开发者ID:parabuild-ci,项目名称:parabuild-ci,代码行数:72,代码来源:DatabaseManagerSwing.java

示例15: verifyParameters

import java.sql.SQLException; //导入方法依赖的package包/类
@Override
protected Result verifyParameters(Map<String, Object> parameters) {
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.PARAMETERS)
        .error(ResultErrorHelper.requiresOption("url", parameters))
        .error(ResultErrorHelper.requiresOption("user", parameters))
        .error(ResultErrorHelper.requiresOption("password", parameters));

    if (builder.build().getErrors().isEmpty()) {
        try (Connection connection = 
            DriverManager.getConnection(
                    parameters.get("url").toString(), 
                    String.valueOf(parameters.get("user")), 
                    String.valueOf(parameters.get("password")))) {
            // just try to get the connection
        } catch (SQLException e) {
            final Map<String, Object> redacted = new HashMap<>(parameters);
            redacted.replace("password", "********");
            LOG.warn("Unable to connecto to database with parameters {}, SQLSTATE: {}, error code: {}",
                redacted, e.getSQLState(), e.getErrorCode(), e);

            final String sqlState = e.getSQLState();
            if (sqlState == null || sqlState.length() < 2) {
                unsupportedDatabase(builder);
            } else {
                switch (sqlState.substring(0, 2)) {
                case "28":
                    builder.error(ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
                        .parameterKey("user")
                        .parameterKey("password")
                        .build());
                    break;
                case "08":
                case "3D":
                    builder.error(ResultErrorBuilder.withCodeAndDescription(
                        VerificationError.StandardCode.ILLEGAL_PARAMETER_VALUE, e.getMessage())
                        .parameterKey("url")
                        .build());
                    break;
                default:
                    builder.error(ResultErrorBuilder.withCodeAndDescription(
                        VerificationError.StandardCode.GENERIC, e.getMessage())
                        .build());
                    break;
                }
            }
        }
    }
    return builder.build();
}
 
开发者ID:syndesisio,项目名称:connectors,代码行数:50,代码来源:SqlStoredConnectorVerifierExtension.java


注:本文中的java.sql.SQLException.getSQLState方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。