Example usage for java.sql SQLException getSQLState

List of usage examples for java.sql SQLException getSQLState

Introduction

In this page you can find the example usage for java.sql SQLException getSQLState.

Prototype

public String getSQLState() 

Source Link

Document

Retrieves the SQLState for this SQLException object.

Usage

From source file:je3.rmi.MudClient.java

 /** Deposit the specified money into the named account */
 public synchronized void deposit(String name, String password, 
              FunnyMoney money) //from  www .  j a  v a  2  s.  c om
throws RemoteException, BankingException
 {
     int balance = 0; 
     Statement s = null;
     try {
         balance = verify(name, password);
         s = db.createStatement();
         // Update the balance
         s.executeUpdate("UPDATE accounts " +
          "SET balance = " + balance + money.amount + " " +
          "WHERE name='" + name + "' " +
          "  AND password = '" + password + "'");
         // Add a row to the transaction history
         s.executeUpdate("INSERT INTO " + name + "_history " + 
          "VALUES ('Deposited " + money.amount + 
          " at " + new Date() + "')");
         db.commit();
     }
     catch (SQLException e) {
         try { db.rollback(); } catch (Exception e2) {}
         throw new BankingException("SQLException: " + e.getMessage() + 
                ": " + e.getSQLState());
     }
     finally { try { s.close(); } catch (Exception e) {} }
 }

From source file:je3.rmi.MudClient.java

 /** Get the transaction history of the named account */
 public synchronized List getTransactionHistory(String name, 
                  String password)
throws RemoteException, BankingException
 {
     Statement s = null;//from  w w w. ja  va  2  s .c o m
     List list = new ArrayList();
     try {
         // Call verify to check the password, even though we don't 
         // care what the current balance is.
         verify(name, password);
         s = db.createStatement();
         // Request everything out of the history table
         s.executeQuery("SELECT * from " + name + "_history");
         // Get the results of the query and put them in a Vector
         ResultSet r = s.getResultSet();
         while(r.next()) list.add(r.getString(1));
         // Commit the transaction
         db.commit();
     }
     catch (SQLException e) {
         try { db.rollback(); } catch (Exception e2) {}
         throw new BankingException("SQLException: " + e.getMessage() + 
                ": " + e.getSQLState());
     }
     finally { try { s.close(); } catch (Exception e) {} }
     // Return the Vector of transaction history.
     return list;
 }

From source file:je3.rmi.MudClient.java

 /** Withdraw the specified amount from the named account */
 public synchronized FunnyMoney withdraw(String name, String password, 
                int amount)
throws RemoteException, BankingException
 {
     int balance = 0;
     Statement s = null;//from   w w w.java 2  s . c om
     try {
         balance = verify(name, password);
         if (balance < amount)
   throw new BankingException("Insufficient Funds");
         s = db.createStatement();
         // Update the account balance
         s.executeUpdate("UPDATE accounts " +
          "SET balance = " + (balance - amount) + " " +
          "WHERE name='" + name + "' " +
          "  AND password = '" + password + "'");
         // Add a row to the transaction history
         s.executeUpdate("INSERT INTO " + name + "_history " + 
          "VALUES ('Withdrew " + amount + 
          " at " + new Date() + "')");
         db.commit();
     }
     catch (SQLException e) {
         try { db.rollback(); } catch (Exception e2) {}
         throw new BankingException("SQLException: " + e.getMessage() + 
                ": " + e.getSQLState());
     }
     finally { try { s.close(); } catch (Exception e) {} }
   
     return new FunnyMoney(amount);
 }

From source file:tds.dll.mysql.RtsPackageDLL.java

/**
 * Creates or updates a new record.//from w w w .  ja  va2 s .c o  m
 * 
 * @param connection
 * @param entityType
 * @param key
 * @param clientName
 * @param xmlPackage
 * @return number of records created
 * @throws ReturnStatusException
 */
private int createOrUpdate(SQLConnection connection, EntityType entityType, Long key, String clientName,
        InputStream packageStream, String version, List<TestType> testTypes) throws ReturnStatusException {
    String SQL_INSERT = null;
    if (entityType == EntityType.PROCTOR) {
        SQL_INSERT = "insert into r_proctorpackage (ProctorKey, ClientName, Package, Version, DateCreated, TestType) values (?, ?, ?, ?, now(), ?) on duplicate key update Package=VALUES(Package), DateCreated=VALUES(DateCreated), TestType=VALUES(TestType)";
    } else {
        SQL_INSERT = "insert into r_studentpackage (StudentKey, ClientName, Package, Version, DateCreated) values (?, ?, ?, ?, now()) on duplicate key update Package=VALUES(Package), DateCreated=VALUES(DateCreated)";
    }
    try (PreparedStatement preparedStatement = connection.prepareStatement(SQL_INSERT)) {
        preparedStatement.setLong(1, key);
        preparedStatement.setString(2, clientName);
        preparedStatement.setBinaryStream(3, packageStream);
        preparedStatement.setString(4, version);
        if (entityType == EntityType.PROCTOR) {
            preparedStatement.setString(5, StringUtils.join(testTypes, ","));
        }
        preparedStatement.execute();
        return 1;
    } catch (SQLException e) {
        _logger.error(e.getMessage() + "; SQLState: " + e.getSQLState(), e);
        throw new ReturnStatusException("could not create " + entityType.getValue() + ": " + e.getMessage());
    }
}

From source file:com.evolveum.midpoint.repo.sql.SqlBaseService.java

private boolean isExceptionRelatedToSerialization(Exception ex) {

    if (ex instanceof SerializationRelatedException || ex instanceof PessimisticLockException
            || ex instanceof LockAcquisitionException
            || ex instanceof HibernateOptimisticLockingFailureException
            || ex instanceof StaleObjectStateException) { // todo the last one is questionable
        return true;
    }/*from  w ww  . j a  v a2 s .c om*/

    // it's not locking exception (optimistic, pesimistic lock or simple lock acquisition) understood by hibernate
    // however, it still could be such exception... wrapped in e.g. TransactionException
    // so we have a look inside - we try to find SQLException there

    SQLException sqlException = findSqlException(ex);
    if (sqlException == null) {
        return false;
    }

    // these error codes / SQL states we consider related to locking:
    //  code 50200 [table timeout lock in H2, 50200 is LOCK_TIMEOUT_1 error code]
    //  code 40001 [DEADLOCK_1 in H2]
    //  state 40001 [serialization failure in PostgreSQL - http://www.postgresql.org/docs/9.1/static/transaction-iso.html - and probably also in other systems]
    //  state 40P01 [deadlock in PostgreSQL]
    //  code ORA-08177: can't serialize access for this transaction in Oracle
    //  code ORA-01466 ["unable to read data - table definition has changed"] in Oracle
    //  code ORA-01555: snapshot too old: rollback segment number  with name "" too small
    //  code ORA-22924: snapshot too old
    //
    // sql states should be somewhat standardized; sql error codes are vendor-specific
    // todo: so it is probably not very safe to test for codes without testing for specific database (h2, oracle)
    // but the risk of problem is quite low here, so let it be...

    // strange exception occurring in MySQL when doing multithreaded org closure maintenance
    // alternatively we might check for error code = 1030, sql state = HY000
    // but that would cover all cases of "Got error XYZ from storage engine"
    if (getConfiguration().isUsingMySQL() && sqlException.getMessage() != null
            && sqlException.getMessage().contains("Got error -1 from storage engine")) {
        return true;
    }

    return sqlException.getErrorCode() == 50200 || sqlException.getErrorCode() == 40001
            || "40001".equals(sqlException.getSQLState()) || "40P01".equals(sqlException.getSQLState())
            || sqlException.getErrorCode() == 8177 || sqlException.getErrorCode() == 1466
            || sqlException.getErrorCode() == 1555 || sqlException.getErrorCode() == 22924
            || sqlException.getErrorCode() == 3960; // Snapshot isolation transaction aborted due to update conflict.
}

From source file:org.jumpmind.symmetric.service.impl.DataExtractorService.java

public void extractToStaging(ProcessInfo processInfo, Node targetNode, OutgoingBatch batch) {
    try {/* ww w. ja v a 2s. co  m*/
        final ExtractMode MODE = ExtractMode.FOR_SYM_CLIENT;
        if (batch.isExtractJobFlag() && batch.getStatus() != Status.IG) {
            // TODO should we get rid of extract in background and just
            // extract here
            throw new IllegalStateException("TODO");
        } else {
            processInfo.setStatus(ProcessInfo.Status.EXTRACTING);
            processInfo.setDataCount(batch.getDataEventCount());
            processInfo.setCurrentBatchId(batch.getBatchId());
            processInfo.setCurrentLoadId(batch.getLoadId());
            batch = extractOutgoingBatch(processInfo, targetNode, null, batch, true, true, MODE);
        }

        if (batch.getStatus() != Status.OK) {
            batch.setLoadCount(batch.getLoadCount() + 1);
            changeBatchStatus(Status.LD, batch, MODE);
        }

    } catch (RuntimeException e) {
        SQLException se = unwrapSqlException(e);
        /* Reread batch in case the ignore flag has been set */
        batch = outgoingBatchService.findOutgoingBatch(batch.getBatchId(), batch.getNodeId());
        statisticManager.incrementDataExtractedErrors(batch.getChannelId(), 1);
        if (se != null) {
            batch.setSqlState(se.getSQLState());
            batch.setSqlCode(se.getErrorCode());
            batch.setSqlMessage(se.getMessage());
        } else {
            batch.setSqlMessage(getRootMessage(e));
        }
        batch.revertStatsOnError();
        if (batch.getStatus() != Status.IG && batch.getStatus() != Status.OK) {
            batch.setStatus(Status.ER);
            batch.setErrorFlag(true);
        }
        outgoingBatchService.updateOutgoingBatch(batch);

        if (e instanceof ProtocolException) {
            IStagedResource resource = getStagedResource(batch);
            if (resource != null) {
                resource.delete();
            }
        }
        log.error("Failed to extract batch {}", batch, e);
        processInfo.setStatus(ProcessInfo.Status.ERROR);
    }
}

From source file:org.getobjects.eoaccess.EOAdaptorChannel.java

/**
 * Executes a SQL update expression, eg an INSERT, UPDATE or DELETE.
 * //  w  ww . j av a 2s .  c o m
 * If the operation fails, the method returns -1 and sets the lastException
 * to the caught error.
 * 
 * @param _s - the formatted SQL expression
 * @return the number of affected records, or -1 if something failed
 */
public int evaluateUpdateExpression(final EOSQLExpression _s) {
    if (_s == null) {
        log.error("evaluateUpdateExpression caller gave us no expr ...");
        return -1;
    }

    this.lastException = null;

    final String sql = _s.statement();
    if (sql == null) {
        log.error("evaluateUpdateExpression param is invalid expr: " + _s);
        return -1;
    }

    /* we always prepare for updates to improve escaping behaviour */

    final List<Map<String, Object>> binds = _s.bindVariableDictionaries();

    if (sqllog.isInfoEnabled()) {
        sqllog.info(sql);
        sqllog.info("binds: " + binds);
    }
    PreparedStatement stmt = this._prepareStatementWithBinds(sql, binds);

    if (stmt == null) {
        log.error("could not create prepared statement for expression: " + _s);
        return -1;
    }

    /* perform update */

    int updateCount = 0;
    try {
        /* execute */
        updateCount = stmt.executeUpdate();
    } catch (SQLException e) {
        /**
         * PG: 0A000 = "cannot insert into a view" (INSERT on view)
         * PG: 42804 = "column XYZ is of type numeric but expression is of type
         *              character varying"
         * PG: 23502 = "null value in column "x" violates not-null constraint"
         */
        this.lastException = e;

        String sqlState = e.getSQLState();
        if (sqlState != null && sqlState.equals("0A000")) // TBD: wrap exception?
            log.error("cannot insert into a view: " + _s, e);
        else if (sqlState != null && sqlState.equals("23505")) {
            /* PG: "duplicate key violates unique constraint" */
            // TBD: can we extract the failed contraint from the PSQLException?
            log.error("dupkey violates unique constraints: " + _s + "\nSQL: " + sql, e);
        } else if (sqlState != null && sqlState.equals("22P05")) {
            /* PG:
             * character 0xe2889a of encoding "UTF8" has no equivalent in "LATIN1"
             * 
             * (attempt to insert a Unicode char into a LATIN1 database. Usually
             * incorrect charset configuration).
             */
            log.error("values to be inserted/updated contain characters "
                    + "which are unsupported by the database: " + binds, e);
        } else
            log.error("could not perform update expression " + sqlState + ": " + _s, e);

        return -1;
    } catch (NullPointerException e) {
        /* Note: this happens in the MySQL adaptor if the statement got closed in
         *       the meantime. (TODO: closed by whom?)
         */
        this.lastException = e;
        log.error("could not perform update statement (null ptr): " + _s, e);
        return -1;
    } finally {
        this._releaseResources(stmt, null);
    }

    if (log.isDebugEnabled())
        log.debug("affected objects: " + updateCount);

    return updateCount;
}

From source file:je3.rmi.MudClient.java

 /** Open an account */
 public synchronized void openAccount(String name, String password)
throws RemoteException, BankingException
 {
     // First, check if there is already an account with that name
     Statement s = null;//from   ww w .  j a v a  2  s.com
     try { 
         s = db.createStatement();
         s.executeQuery("SELECT * FROM accounts WHERE name='" + name + "'");
         ResultSet r = s.getResultSet();
         if (r.next()) throw new BankingException("Account name in use.");
       
         // If it doesn't exist, go ahead and create it Also, create a
         // table for the transaction history of this account and insert an
         // initial transaction into it.
         s = db.createStatement();
         s.executeUpdate("INSERT INTO accounts VALUES ('" + name + "', '" +
          password + "', 0)");
         s.executeUpdate("CREATE TABLE " + name + 
          "_history (msg VARCHAR(80))");
         s.executeUpdate("INSERT INTO " + name + "_history " +
          "VALUES ('Account opened at " + new Date() + "')");
       
         // And if we've been successful so far, commit these updates,
         // ending the atomic transaction.  All the methods below also use
         // this atomic transaction commit/rollback scheme
         db.commit();
     }
     catch(SQLException e) {
         // If an exception was thrown, "rollback" the prior updates,
         // removing them from the database.  This also ends the atomic
         // transaction.
         try { db.rollback(); } catch (Exception e2) {}
         // Pass the SQLException on in the body of a BankingException
         throw new BankingException("SQLException: " + e.getMessage() + 
                ": " + e.getSQLState());
     }
     // No matter what happens, don't forget to close the DB Statement
     finally { try { s.close(); } catch (Exception e) {} }
 }

From source file:com.splicemachine.derby.impl.sql.execute.operations.export.ExportOperationIT.java

@Test
public void export_throwsSQLException_givenBadArguments() throws Exception {
    // export path
    try {//from ww  w .  ja v a  2  s .c o m
        methodWatcher.executeQuery("export('', false, null,null,null, null) select 1 from sys.sysaliases ");
        fail();
    } catch (SQLException e) {
        assertEquals("Invalid parameter 'export path'=''.", e.getMessage());
    }

    // encoding
    try {
        methodWatcher.executeQuery(
                "export('/tmp/', false, 1,'BAD_ENCODING',null, null) select 1 from sys.sysaliases ");
        fail();
    } catch (SQLException e) {
        assertEquals("Invalid parameter 'encoding'='BAD_ENCODING'.", e.getMessage());
    }

    // field delimiter
    try {
        methodWatcher
                .executeQuery("export('/tmp/', false, 1,'utf-8','AAA', null) select 1 from sys.sysaliases ");
        fail();
    } catch (SQLException e) {
        assertEquals("Invalid parameter 'field delimiter'='AAA'.", e.getMessage());
    }

    // quote character
    try {
        methodWatcher
                .executeQuery("export('/tmp/', false, 1,'utf-8',',', 'BBB') select 1 from sys.sysaliases ");
        fail();
    } catch (SQLException e) {
        assertEquals("Invalid parameter 'quote character'='BBB'.", e.getMessage());
    }

    // no permission to create export dir
    try {
        methodWatcher.executeQuery(
                "export('/ExportOperationIT/', false, 1,'utf-8',null, null) select 1 from sys.sysaliases ");
        fail();
    } catch (SQLException e) {
        assertEquals("Invalid parameter 'cannot create export directory'='/ExportOperationIT/'.",
                e.getMessage());
    }

    // wrong replica count
    try {
        methodWatcher
                .executeQuery("export('/tmp/', false, -100, null, null, null) select 1 from sys.sysaliases ");
        fail();
    } catch (SQLException e) {
        assertEquals("Invalid error state", "XIE0U", e.getSQLState());
    }

    // wrong field separator
    try {
        methodWatcher
                .executeQuery("export('/tmp/', false, null, null, 10, null) select 1 from sys.sysaliases ");
        fail();
    } catch (SQLException e) {
        assertEquals("Invalid error state", "XIE0X", e.getSQLState());
        assertEquals("Invalid error message",
                "The export operation was not performed, because value of the specified parameter (10) is wrong.",
                e.getMessage());
    }

    // wrong quote character
    try {
        methodWatcher
                .executeQuery("export('/tmp/', false, null, null, null, 100) select 1 from sys.sysaliases ");
        fail();
    } catch (SQLException e) {
        assertEquals("Invalid error state", "XIE0X", e.getSQLState());
        assertEquals("Invalid error message",
                "The export operation was not performed, because value of the specified parameter (100) is wrong.",
                e.getMessage());
    }

    // wrong replication parameter
    try {
        methodWatcher
                .executeQuery("export('/tmp/', false, 'a', null, null, null) select 1 from sys.sysaliases ");
        fail();
    } catch (SQLException e) {
        assertEquals("Invalid error state", "XIE0X", e.getSQLState());
        assertEquals("Invalid error message",
                "The export operation was not performed, because value of the specified parameter (a) is wrong.",
                e.getMessage());
    }
}

From source file:org.lockss.db.DbManager.java

/**
 * Shuts down the Derby database.// w ww  .  java  2  s .co m
 * 
 * @throws SQLException
 *           if there are problems shutting down the database.
 */
private void shutdownDerbyDb(Configuration dsConfig) throws DbException {
    final String DEBUG_HEADER = "shutdownDerbyDb(): ";
    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "Starting...");

    // Modify the datasource configuration for shutdown.
    Configuration shutdownConfig = dsConfig.copy();
    shutdownConfig.remove("createDatabase");
    shutdownConfig.put("shutdownDatabase", "shutdown");

    // Create the shutdown datasource.
    DataSource ds = createDataSource(shutdownConfig.get("className"));

    // Initialize the shutdown datasource properties.
    initializeDataSourceProperties(shutdownConfig, ds);

    // Get a connection, which will shutdown the Derby database.
    try {
        dbManagerSql.getConnection(ds, false);
    } catch (SQLException sqle) {
        // Check whether it is the expected exception.
        if (SHUTDOWN_SUCCESS_STATE_CODE.equals(sqle.getSQLState())) {
            // Yes.
            if (log.isDebug3())
                log.debug3(DEBUG_HEADER + "Expected exception caught", sqle);
        } else {
            // No: Report the problem.
            log.error("Unexpected exception caught shutting down database", sqle);
        }
    } catch (RuntimeException re) {
        // Report the problem.
        log.error("Unexpected exception caught shutting down database", re);
    }

    if (log.isDebug())
        log.debug(DEBUG_HEADER + "Derby database has been shutdown.");
    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "Done.");
}