Java Code Examples for java.sql.SQLException.getSQLState()

The following are Jave code examples for showing how to use getSQLState() of the java.sql.SQLException class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: OpenDiabetes   File: TestUtil.java   View Source Code Vote up 6 votes
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;
    }
 
Example 2
Project: HTAPBench   File: ClientBalancer.java   View Source Code Vote up 6 votes
/**
 * 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;
        }    
    }
}
 
Example 3
Project: aliyun-maxcompute-data-collectors   File: SQLServerConnectionFailureHandler.java   View Source Code Vote up 6 votes
/**
 * 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;
}
 
Example 4
Project: ChronoBike   File: SQLCall.java   View Source Code Vote up 6 votes
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);
	}
}
 
Example 5
Project: sstore-soft   File: BaseConnectionWrapper.java   View Source Code Vote up 5 votes
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);
}
 
Example 6
Project: HTAPBench   File: GenericQuery.java   View Source Code Vote up 5 votes
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;

}
 
Example 7
Project: message-broker   File: RdbmsCoordinationDaoImpl.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 8
Project: BibliotecaPS   File: StandardLoadBalanceExceptionChecker.java   View Source Code Vote up 5 votes
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;
}
 
Example 9
Project: lams   File: ExtendedMysqlExceptionSorter.java   View Source Code Vote up 5 votes
@Override
public boolean isExceptionFatal(SQLException ex) {
    String sqlState = ex.getSQLState();

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

    return super.isExceptionFatal(ex);
}
 
Example 10
Project: s-store   File: BaseConnectionWrapper.java   View Source Code Vote up 5 votes
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);
}
 
Example 11
Project: s-store   File: BaseConnectionWrapper.java   View Source Code Vote up 5 votes
public void setClientInfo(
        Properties properties) throws SQLClientInfoException {

    try {
        validate();
    } catch (SQLException e) {
        throw new SQLClientInfoException(e.getMessage(), e.getSQLState(),
                e.getErrorCode(), (Map<String, ClientInfoStatus>) null, e);
    }
    this.getConnection().setClientInfo(properties);
}
 
Example 12
Project: sstore-soft   File: DatabaseManager.java   View Source Code Vote up 4 votes
/**
 * 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();
}
 
Example 13
Project: aliyun-maxcompute-data-collectors   File: SQLServerAsyncDBExecThread.java   View Source Code Vote up 4 votes
/**
 * 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.");
  }
}
 
Example 14
Project: BibliotecaPS   File: ConnectionImpl.java   View Source Code Vote up 4 votes
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;
}
 
Example 15
Project: goku-jdbc   File: GokuSQLException.java   View Source Code Vote up 4 votes
public GokuSQLException(SQLException orig) {
    super(orig.getMessage(), orig.getSQLState(), orig.getErrorCode(), orig);
}
 
Example 16
Project: parabuild-ci   File: DatabaseManagerSwing.java   View Source Code Vote up 4 votes
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();
            }
        }
    }
 
Example 17
Project: connectors   File: SqlStoredConnectorVerifierExtension.java   View Source Code Vote up 4 votes
@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();
}
 
Example 18
Project: s-store   File: DatabaseManager.java   View Source Code Vote up 4 votes
/**
 * 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();
}
 
Example 19
Project: ChronoBike   File: CSQLStatus.java   View Source Code Vote up 4 votes
public void setSQLCode(SQLException e)
{
	reset();
	m_nSQLCode = e.getErrorCode();
	m_csReason = "SQL Exception (" + m_nSQLCode + "):" + e.getMessage()  + " SQLState="+ e.getSQLState();
}
 
Example 20
Project: morf   File: RuntimeSqlException.java   View Source Code Vote up 2 votes
/**
 * Creates an SQL runtime exception based on an underlying exception.
 *
 * @param e Underlying exception.
 */
public RuntimeSqlException(SQLException e) {
  super(e.getMessage() + ": Error code [" + e.getErrorCode() + "] SQL state [" + e.getSQLState() + "]", e);
}