當前位置: 首頁>>代碼示例>>Java>>正文


Java SQLException.getErrorCode方法代碼示例

本文整理匯總了Java中java.sql.SQLException.getErrorCode方法的典型用法代碼示例。如果您正苦於以下問題:Java SQLException.getErrorCode方法的具體用法?Java SQLException.getErrorCode怎麽用?Java SQLException.getErrorCode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.sql.SQLException的用法示例。


在下文中一共展示了SQLException.getErrorCode方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: cargarDatos

import java.sql.SQLException; //導入方法依賴的package包/類
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());
		}
	}
}
 
開發者ID:JuandeLS3,項目名稱:Library-app,代碼行數:20,代碼來源:GestionLibros.java

示例2: setClientInfo

import java.sql.SQLException; //導入方法依賴的package包/類
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);
}
 
開發者ID:s-store,項目名稱:s-store,代碼行數:12,代碼來源:BaseConnectionWrapper.java

示例3: extractErrorCode

import java.sql.SQLException; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:16,代碼來源:JdbcExceptionHelper.java

示例4: validateImpl

import java.sql.SQLException; //導入方法依賴的package包/類
/**
 * 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;
        }
    }
}
 
開發者ID:Microsoft,項目名稱:elastic-db-tools-for-java,代碼行數:38,代碼來源:ShardMapManagerLoadTests.java

示例5: interceptException

import java.sql.SQLException; //導入方法依賴的package包/類
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;
}
 
開發者ID:bragex,項目名稱:the-vigilantes,代碼行數:8,代碼來源:ConnectionRegressionTest.java

示例6: hasDeadlockOrTimeoutRolledBackTx

import java.sql.SQLException; //導入方法依賴的package包/類
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;
    }
}
 
開發者ID:bragex,項目名稱:the-vigilantes,代碼行數:14,代碼來源:StatementImpl.java

示例7: 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

示例8: 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

示例9: rollback

import java.sql.SQLException; //導入方法依賴的package包/類
/**
 * @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();
        }
    }
}
 
開發者ID:rafallis,項目名稱:BibliotecaPS,代碼行數:78,代碼來源:ConnectionImpl.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,項目名稱:s-store,代碼行數:66,代碼來源:DatabaseManager.java

示例11: compareResults

import java.sql.SQLException; //導入方法依賴的package包/類
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);
}
 
開發者ID:parabuild-ci,項目名稱:parabuild-ci,代碼行數:61,代碼來源:TestGroupByHaving.java

示例12: 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:s-store,項目名稱:sstore-soft,代碼行數:72,代碼來源:DatabaseManagerSwing.java

示例13: DBConnectionException

import java.sql.SQLException; //導入方法依賴的package包/類
public DBConnectionException(String uri, SQLException e) {
  super("Connection URI:" + uri + "; " + e.getMessage(), e.getSQLState(), e.getErrorCode(), e.getCause());
}
 
開發者ID:twosigma,項目名稱:beaker-notebook-archive,代碼行數:4,代碼來源:DBConnectionException.java

示例14: RuntimeSqlException

import java.sql.SQLException; //導入方法依賴的package包/類
/**
 * 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);
}
 
開發者ID:alfasoftware,項目名稱:morf,代碼行數:10,代碼來源:RuntimeSqlException.java


注:本文中的java.sql.SQLException.getErrorCode方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。