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

The following are Jave code examples for showing how to use getErrorCode() 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: Library-app   File: GestionLibros.java   View Source Code Vote up 6 votes
private void cargarDatos() {
	try {
		stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
		String sql="select * from libro";
		rset=stmt.executeQuery(sql);	// Ejecutamos consulta
		rset.next();				// Pasamos de registro
		totalRegistros();
		mostrarDatos();	
	} catch (SQLException e) {
		if(e.getErrorCode()==17011){
			JOptionPane.showMessageDialog(null, "No hay ning´┐Żn registro en la base de datos, cree uno!");
			setBotones(false);
			setText(false);
			btnNuevo.setEnabled(true);
		} else {
		JOptionPane.showMessageDialog(null, e.getMessage() + " " + e.getErrorCode());
		}
	}
}
 
Example 2
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 3
Project: lams   File: JdbcExceptionHelper.java   View Source Code Vote up 5 votes
/**
 * For the given SQLException, locates the vendor-specific error code.
 *
 * @param sqlException The exception from which to extract the SQLState
 * @return The error code.
 */
public static int extractErrorCode(SQLException sqlException) {
	int errorCode = sqlException.getErrorCode();
	SQLException nested = sqlException.getNextException();
	while ( errorCode == 0 && nested != null ) {
		errorCode = nested.getErrorCode();
		nested = nested.getNextException();
	}
	return errorCode;
}
 
Example 4
Project: sstore-soft   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 5
Project: elastic-db-tools-for-java   File: ShardMapManagerLoadTests.java   View Source Code Vote up 5 votes
/**
 * Helper function to do validation, this will be called using TFH retry policy.
 *
 * @param sm
 *            Shard map for a mapping to validate
 * @param key
 *            Key to lookup and validate
 */
private static void validateImpl(ShardMap sm,
        int key) throws SQLException {
    try (Connection conn = sm.openConnectionForKey(key, Globals.SHARD_USER_CONN_STRING, ConnectionOptions.Validate)) {
        conn.close();
    }
    catch (SQLException e) {
        // Error Number 3980: The request failed to run because the batch is aborted, this can be
        // caused by abort signal sent from client, or another request is running in the same session,
        // which makes the session busy.
        // Error Number = 0, Class = 20, Message = The connection is broken and recovery is not
        // possible. The connection is marked by the server as unrecoverable. No attempt was made to
        // restore the connection.
        // Error Number = 0, Class = 11, Message = A severe error occurred on the current command.
        // The results, if any, should be discarded.
        switch (e.getErrorCode()) {
            case 0:
                if (e.getErrorCode() != 20 && e.getErrorCode() != 11) {
                    throw e;
                }
                break;

            case 3980:
                break;

            default:
                throw e;
        }
    }
}
 
Example 6
Project: the-vigilantes   File: ConnectionRegressionTest.java   View Source Code Vote up 5 votes
public SQLException interceptException(SQLException sqlEx, com.mysql.jdbc.Connection conn) {
    if (sqlEx.getErrorCode() == 1295 || sqlEx.getMessage().contains("This command is not supported in the prepared statement protocol yet")) {
        // SQLException will not be re-thrown if emulateUnsupportedPstmts=true, thus throw RuntimeException to fail the test
        throw new RuntimeException(sqlEx);
    }
    return sqlEx;
}
 
Example 7
Project: the-vigilantes   File: StatementImpl.java   View Source Code Vote up 5 votes
protected final boolean hasDeadlockOrTimeoutRolledBackTx(SQLException ex) {
    int vendorCode = ex.getErrorCode();

    switch (vendorCode) {
        case MysqlErrorNumbers.ER_LOCK_DEADLOCK:
        case MysqlErrorNumbers.ER_LOCK_TABLE_FULL:
            return true;
        case MysqlErrorNumbers.ER_LOCK_WAIT_TIMEOUT:
            return !this.version5013OrNewer;
        default:
            return false;
    }
}
 
Example 8
Project: ProyectoPacientes   File: ConnectionRegressionTest.java   View Source Code Vote up 5 votes
public SQLException interceptException(SQLException sqlEx, com.mysql.jdbc.Connection conn) {
    if (sqlEx.getErrorCode() == 1295 || sqlEx.getMessage().contains("This command is not supported in the prepared statement protocol yet")) {
        // SQLException will not be re-thrown if emulateUnsupportedPstmts=true, thus throw RuntimeException to fail the test
        throw new RuntimeException(sqlEx);
    }
    return sqlEx;
}
 
Example 9
Project: BibliotecaPS   File: StatementImpl.java   View Source Code Vote up 5 votes
protected final boolean hasDeadlockOrTimeoutRolledBackTx(SQLException ex) {
    int vendorCode = ex.getErrorCode();

    switch (vendorCode) {
        case MysqlErrorNumbers.ER_LOCK_DEADLOCK:
        case MysqlErrorNumbers.ER_LOCK_TABLE_FULL:
            return true;
        case MysqlErrorNumbers.ER_LOCK_WAIT_TIMEOUT:
            return !this.version5013OrNewer;
        default:
            return false;
    }
}
 
Example 10
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 11
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 12
Project: BibliotecaPS   File: ConnectionImpl.java   View Source Code Vote up 4 votes
/**
 * @see Connection#rollback(Savepoint)
 */
public void rollback(final Savepoint savepoint) throws SQLException {

    synchronized (getConnectionMutex()) {
        if (versionMeetsMinimum(4, 0, 14) || versionMeetsMinimum(4, 1, 1)) {
            checkClosed();

            try {
                if (this.connectionLifecycleInterceptors != null) {
                    IterateBlock<Extension> iter = new IterateBlock<Extension>(this.connectionLifecycleInterceptors.iterator()) {

                        @Override
                        void forEach(Extension each) throws SQLException {
                            if (!((ConnectionLifecycleInterceptor) each).rollback(savepoint)) {
                                this.stopIterating = true;
                            }
                        }
                    };

                    iter.doForAll();

                    if (!iter.fullIteration()) {
                        return;
                    }
                }

                StringBuilder rollbackQuery = new StringBuilder("ROLLBACK TO SAVEPOINT ");
                rollbackQuery.append('`');
                rollbackQuery.append(savepoint.getSavepointName());
                rollbackQuery.append('`');

                java.sql.Statement stmt = null;

                try {
                    stmt = getMetadataSafeStatement();

                    stmt.executeUpdate(rollbackQuery.toString());
                } catch (SQLException sqlEx) {
                    int errno = sqlEx.getErrorCode();

                    if (errno == 1181) {
                        String msg = sqlEx.getMessage();

                        if (msg != null) {
                            int indexOfError153 = msg.indexOf("153");

                            if (indexOfError153 != -1) {
                                throw SQLError.createSQLException("Savepoint '" + savepoint.getSavepointName() + "' does not exist",
                                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT, errno, getExceptionInterceptor());
                            }
                        }
                    }

                    // We ignore non-transactional tables if told to do so
                    if (getIgnoreNonTxTables() && (sqlEx.getErrorCode() != SQLError.ER_WARNING_NOT_COMPLETE_ROLLBACK)) {
                        throw sqlEx;
                    }

                    if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE.equals(sqlEx.getSQLState())) {
                        throw SQLError.createSQLException("Communications link failure during rollback(). Transaction resolution unknown.",
                                SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN, getExceptionInterceptor());
                    }

                    throw sqlEx;
                } finally {
                    closeStatement(stmt);
                }
            } finally {
                this.needsPing = this.getReconnectAtTxEnd();
            }
        } else {
            throw SQLError.createSQLFeatureNotSupportedException();
        }
    }
}
 
Example 13
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 14
Project: parabuild-ci   File: TestGroupByHaving.java   View Source Code Vote up 4 votes
private void compareResults(String sql, Object[][] rows,
                            int errorCode) throws SQLException {

    ResultSet rs = null;

    try {
        rs = stmt.executeQuery(sql);

        assertTrue("Statement <" + sql + "> \nexpecting error code: "
                   + errorCode, (0 == errorCode));
    } catch (SQLException sqlx) {
        if (sqlx.getErrorCode() != errorCode) {
            sqlx.printStackTrace();
        }

        assertTrue("Statement <" + sql + "> \nthrows wrong error code: "
                   + sqlx.getErrorCode() + " expecting error code: "
                   + errorCode, (sqlx.getErrorCode() == errorCode));

        return;
    }

    int rowCount = 0;
    int colCount = rows.length > 0 ? rows[0].length
                                   : 0;

    while (rs.next()) {
        assertTrue("Statement <" + sql + "> \nreturned too many rows.",
                   (rowCount < rows.length));

        Object[] columns = rows[rowCount];

        for (int col = 1, i = 0; i < colCount; i++, col++) {
            Object result   = null;
            Object expected = columns[i];

            if (expected == null) {
                result = rs.getString(col);
                result = rs.wasNull() ? null
                                      : result;
            } else if (expected instanceof String) {
                result = rs.getString(col);
            } else if (expected instanceof Double) {
                result = new Double(rs.getString(col));
            } else if (expected instanceof Integer) {
                result = new Integer(rs.getInt(col));
            }

            assertEquals("Statement <" + sql
                         + "> \nreturned wrong value.", columns[i],
                             result);
        }

        rowCount++;
    }

    assertEquals("Statement <" + sql
                 + "> \nreturned wrong number of rows.", rows.length,
                     rowCount);
}
 
Example 15
Project: sstore-soft   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 16
Project: lams   File: ConnectionImpl.java   View Source Code Vote up 4 votes
/**
 * @see Connection#rollback(Savepoint)
 */
public void rollback(final Savepoint savepoint) throws SQLException {

    synchronized (getConnectionMutex()) {
        if (versionMeetsMinimum(4, 0, 14) || versionMeetsMinimum(4, 1, 1)) {
            checkClosed();

            try {
                if (this.connectionLifecycleInterceptors != null) {
                    IterateBlock<Extension> iter = new IterateBlock<Extension>(this.connectionLifecycleInterceptors.iterator()) {

                        @Override
                        void forEach(Extension each) throws SQLException {
                            if (!((ConnectionLifecycleInterceptor) each).rollback(savepoint)) {
                                this.stopIterating = true;
                            }
                        }
                    };

                    iter.doForAll();

                    if (!iter.fullIteration()) {
                        return;
                    }
                }

                StringBuilder rollbackQuery = new StringBuilder("ROLLBACK TO SAVEPOINT ");
                rollbackQuery.append('`');
                rollbackQuery.append(savepoint.getSavepointName());
                rollbackQuery.append('`');

                java.sql.Statement stmt = null;

                try {
                    stmt = getMetadataSafeStatement();

                    stmt.executeUpdate(rollbackQuery.toString());
                } catch (SQLException sqlEx) {
                    int errno = sqlEx.getErrorCode();

                    if (errno == 1181) {
                        String msg = sqlEx.getMessage();

                        if (msg != null) {
                            int indexOfError153 = msg.indexOf("153");

                            if (indexOfError153 != -1) {
                                throw SQLError.createSQLException("Savepoint '" + savepoint.getSavepointName() + "' does not exist",
                                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT, errno, getExceptionInterceptor());
                            }
                        }
                    }

                    // We ignore non-transactional tables if told to do so
                    if (getIgnoreNonTxTables() && (sqlEx.getErrorCode() != SQLError.ER_WARNING_NOT_COMPLETE_ROLLBACK)) {
                        throw sqlEx;
                    }

                    if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE.equals(sqlEx.getSQLState())) {
                        throw SQLError.createSQLException("Communications link failure during rollback(). Transaction resolution unknown.",
                                SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN, getExceptionInterceptor());
                    }

                    throw sqlEx;
                } finally {
                    closeStatement(stmt);
                }
            } finally {
                this.needsPing = this.getReconnectAtTxEnd();
            }
        } else {
            throw SQLError.createSQLFeatureNotSupportedException();
        }
    }
}
 
Example 17
Project: OpenVertretung   File: ConnectionImpl.java   View Source Code Vote up 4 votes
/**
 * @see Connection#rollback(Savepoint)
 */
public void rollback(final Savepoint savepoint) throws SQLException {

    synchronized (getConnectionMutex()) {
        if (versionMeetsMinimum(4, 0, 14) || versionMeetsMinimum(4, 1, 1)) {
            checkClosed();

            try {
                if (this.connectionLifecycleInterceptors != null) {
                    IterateBlock<Extension> iter = new IterateBlock<Extension>(this.connectionLifecycleInterceptors.iterator()) {

                        @Override
                        void forEach(Extension each) throws SQLException {
                            if (!((ConnectionLifecycleInterceptor) each).rollback(savepoint)) {
                                this.stopIterating = true;
                            }
                        }
                    };

                    iter.doForAll();

                    if (!iter.fullIteration()) {
                        return;
                    }
                }

                StringBuilder rollbackQuery = new StringBuilder("ROLLBACK TO SAVEPOINT ");
                rollbackQuery.append('`');
                rollbackQuery.append(savepoint.getSavepointName());
                rollbackQuery.append('`');

                java.sql.Statement stmt = null;

                try {
                    stmt = getMetadataSafeStatement();

                    stmt.executeUpdate(rollbackQuery.toString());
                } catch (SQLException sqlEx) {
                    int errno = sqlEx.getErrorCode();

                    if (errno == 1181) {
                        String msg = sqlEx.getMessage();

                        if (msg != null) {
                            int indexOfError153 = msg.indexOf("153");

                            if (indexOfError153 != -1) {
                                throw SQLError.createSQLException("Savepoint '" + savepoint.getSavepointName() + "' does not exist",
                                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT, errno, getExceptionInterceptor());
                            }
                        }
                    }

                    // We ignore non-transactional tables if told to do so
                    if (getIgnoreNonTxTables() && (sqlEx.getErrorCode() != SQLError.ER_WARNING_NOT_COMPLETE_ROLLBACK)) {
                        throw sqlEx;
                    }

                    if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE.equals(sqlEx.getSQLState())) {
                        throw SQLError.createSQLException("Communications link failure during rollback(). Transaction resolution unknown.",
                                SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN, getExceptionInterceptor());
                    }

                    throw sqlEx;
                } finally {
                    closeStatement(stmt);
                }
            } finally {
                this.needsPing = this.getReconnectAtTxEnd();
            }
        } else {
            throw SQLError.createSQLFeatureNotSupportedException();
        }
    }
}
 
Example 18
Project: lams   File: ConnectionImpl.java   View Source Code Vote up 4 votes
/**
 * The method rollback() drops all changes made since the previous
 * commit/rollback and releases any database locks currently held by the
 * Connection.
 * 
 * @exception SQLException
 *                if a database access error occurs
 * @see commit
 */
public void rollback() throws SQLException {
    synchronized (getConnectionMutex()) {
        checkClosed();

        try {
            if (this.connectionLifecycleInterceptors != null) {
                IterateBlock<Extension> iter = new IterateBlock<Extension>(this.connectionLifecycleInterceptors.iterator()) {

                    @Override
                    void forEach(Extension each) throws SQLException {
                        if (!((ConnectionLifecycleInterceptor) each).rollback()) {
                            this.stopIterating = true;
                        }
                    }
                };

                iter.doForAll();

                if (!iter.fullIteration()) {
                    return;
                }
            }
            // no-op if _relaxAutoCommit == true
            if (this.autoCommit && !getRelaxAutoCommit()) {
                throw SQLError.createSQLException("Can't call rollback when autocommit=true", SQLError.SQL_STATE_CONNECTION_NOT_OPEN,
                        getExceptionInterceptor());
            } else if (this.transactionsSupported) {
                try {
                    rollbackNoChecks();
                } catch (SQLException sqlEx) {
                    // We ignore non-transactional tables if told to do so
                    if (getIgnoreNonTxTables() && (sqlEx.getErrorCode() == SQLError.ER_WARNING_NOT_COMPLETE_ROLLBACK)) {
                        return;
                    }
                    throw sqlEx;

                }
            }
        } catch (SQLException sqlException) {
            if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE.equals(sqlException.getSQLState())) {
                throw SQLError.createSQLException("Communications link failure during rollback(). Transaction resolution unknown.",
                        SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN, getExceptionInterceptor());
            }

            throw sqlException;
        } finally {
            this.needsPing = this.getReconnectAtTxEnd();
        }
    }
}
 
Example 19
Project: beaker-notebook-archive   File: DBConnectionException.java   View Source Code Vote up 4 votes
public DBConnectionException(String uri, SQLException e) {
  super("Connection URI:" + uri + "; " + e.getMessage(), e.getSQLState(), e.getErrorCode(), e.getCause());
}
 
Example 20
Project: morf   File: RuntimeSqlException.java   View Source Code Vote up 2 votes
/**
 * Creates an SQL runtime exception based on an underlying exception and an error message to provide context.
 *
 * @param message Message that describes the processing at the time of the exception.
 * @param e Underlying exception.
 */
public RuntimeSqlException(String message, SQLException e) {
  super(message + ": Error code [" + e.getErrorCode() + "] SQL state [" + e.getSQLState() + "]", e);
}