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:IDlook.java

public void connectToDB() {
    try {//from  w  w w  . j  a  v a  2 s .  com
        connection = DriverManager
                .getConnection("jdbc:mysql://192.168.1.25/identification?user=spider&password=spider");
        statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

    } catch (SQLException connectException) {
        System.out.println(connectException.getMessage());
        System.out.println(connectException.getSQLState());
        System.out.println(connectException.getErrorCode());
        System.exit(1);
    }
}

From source file:org.apache.phoenix.schema.stats.NoOpStatsCollectorIT.java

/**
 * Update Statistics SQL statement should be disallowed
 *///from   w w  w.  ja v  a  2s . c  o  m
@Test
public void testStatsCollectionViaSql() throws SQLException {
    String updateStatisticsSql = "UPDATE STATISTICS " + fullTableName;
    LOG.info("Running SQL to collect stats: " + updateStatisticsSql);
    Statement stmt = conn.createStatement();
    try {
        stmt.execute(updateStatisticsSql);
        Assert.fail("Update Statistics SQL should have failed");
    } catch (SQLException e) {
        Assert.assertEquals("StatsCollectionDisabledOnServerException expected", 1401, e.getErrorCode());
        Assert.assertEquals("StatsCollectionDisabledOnServerException expected", "STS01", e.getSQLState());
    }
}

From source file:com.opensymphony.able.filter.SimpleTransactionServletFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    // TODO we could get clever and figure out what URIs are read only transactions etc
    final TransactionTemplate transactionTemplate = (TransactionTemplate) context
            .getBean("transactionTemplate");
    transactionTemplate.setReadOnly(false);

    if (log.isDebugEnabled()) {
        log.debug("Starting a transaction");
    }//w  w w.j av  a 2  s . c  om

    try {
        Exception e = (Exception) transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {
                try {
                    TransactionOutcome outcome = new TransactionOutcome(status, transactionTemplate);
                    TransactionOutcome.setTransactionOutcome(outcome);
                    filterChain.doFilter(request, response);

                    if (outcome.isRollbackOnly()) {
                        log.debug("Outcome is rollback");
                        status.setRollbackOnly();
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("Completing a transaction with rollback: " + status.isRollbackOnly());
                    }
                    return null;
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    return e;
                }
            }
        });

        if (log.isDebugEnabled()) {
            log.debug("End transaction with exception: " + e);
        }

        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e != null) {
            throw new ServletException(e);
        }
    } catch (TransactionException e) {
        Throwable cause = e.getCause();
        if (cause.getCause() != null) {
            cause = cause.getCause();
        }
        ;
        if (cause instanceof JDBCException) {
            JDBCException jdbcException = (JDBCException) cause;
            SQLException sqlException = jdbcException.getSQLException();
            throw new ServletException("Failed to execute: " + jdbcException.getSQL() + ": error: "
                    + sqlException.getSQLState() + ". Reason: " + sqlException, sqlException);
        }
        throw new ServletException(cause);
    } finally {
        TransactionOutcome.setTransactionOutcome(null);
    }
}

From source file:nl.nn.adapterframework.core.IbisException.java

public String getExceptionSpecificDetails(Throwable t) {
    String result = null;//ww w .  jav  a2  s  .com
    if (t instanceof AddressException) {
        AddressException ae = (AddressException) t;
        String parsedString = ae.getRef();
        if (StringUtils.isNotEmpty(parsedString)) {
            result = addPart(result, " ", "[" + parsedString + "]");
        }
        int column = ae.getPos() + 1;
        if (column > 0) {
            result = addPart(result, " ", "at column [" + column + "]");
        }
    }
    if (t instanceof SAXParseException) {
        SAXParseException spe = (SAXParseException) t;
        int line = spe.getLineNumber();
        int col = spe.getColumnNumber();
        String sysid = spe.getSystemId();

        String locationInfo = null;
        if (StringUtils.isNotEmpty(sysid)) {
            locationInfo = "SystemId [" + sysid + "]";
        }
        if (line >= 0) {
            locationInfo = addPart(locationInfo, " ", "line [" + line + "]");
        }
        if (col >= 0) {
            locationInfo = addPart(locationInfo, " ", "column [" + col + "]");
        }
        result = addPart(locationInfo, ": ", result);
    }
    if (t instanceof TransformerException) {
        TransformerException te = (TransformerException) t;
        SourceLocator locator = te.getLocator();
        if (locator != null) {
            int line = locator.getLineNumber();
            int col = locator.getColumnNumber();
            String sysid = locator.getSystemId();

            String locationInfo = null;
            if (StringUtils.isNotEmpty(sysid)) {
                locationInfo = "SystemId [" + sysid + "]";
            }
            if (line >= 0) {
                locationInfo = addPart(locationInfo, " ", "line [" + line + "]");
            }
            if (col >= 0) {
                locationInfo = addPart(locationInfo, " ", "column [" + col + "]");
            }
            result = addPart(locationInfo, ": ", result);
        }
    }
    if (t instanceof SQLException) {
        SQLException sqle = (SQLException) t;
        int errorCode = sqle.getErrorCode();
        String sqlState = sqle.getSQLState();
        if (errorCode != 0) {
            result = addPart("errorCode [" + errorCode + "]", ", ", result);
        }
        if (StringUtils.isNotEmpty(sqlState)) {
            result = addPart("SQLState [" + sqlState + "]", ", ", result);
        }
    }
    return result;
}

From source file:com.btmatthews.maven.plugins.inmemdb.db.derby.DerbyDatabase.java

/**
 * Shutdown the in-memory Apache Derby database by opening a connection with
 * <code>drop=true</code>. If successful this will cause a SQL exception
 * with a SQL State of 08006 and a vendor specific error code of 45000.
 *
 * @param logger Used to report errors and raise exceptions.
 *///  ww  w  .  j  av  a 2s  .c  om
@Override
public void stop(final Logger logger) {

    logger.logInfo("Stopping embedded Derby database");

    if (server != null) {
        final Map<String, String> attributes = new HashMap<String, String>();
        attributes.put(DROP, TRUE);
        try {
            DriverManager.getConnection(getUrl(attributes), getUsername(),
                    getPassword().length() == 0 ? null : getPassword());
        } catch (final SQLException exception) {
            if (exception.getErrorCode() != 45000 || !"08006".equals(exception.getSQLState())) {
                final String message = MessageUtil.getMessage(ERROR_STARTING_SERVER, getDatabaseName());
                logger.logError(message, exception);
                return;
            }
        }
        try {
            server.shutdown();
        } catch (final Exception exception) {
            final String message = MessageUtil.getMessage(ERROR_STOPPING_SERVER, getDatabaseName());
            logger.logError(message, exception);
            return;
        }
    }

    logger.logInfo("Stopped embedded Derby database");
}

From source file:eu.optimis.aggregator.test.AggregatorPushTest.java

private int getResourceQueryCount(String query) {
    DBConnection dbconn = new DBConnection();
    Connection conn = dbconn.getConnection();
    int count = 0;
    try {//from  www  .  j  a v a 2s .  c  om
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(query);
        rs.next();
        count = rs.getInt("COUNT");
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("SQLException:" + e.getMessage() + ":" + e.getSQLState());
    } finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
    return count;
}

From source file:org.nuxeo.ecm.core.storage.sql.VCSLockManager.java

protected boolean shouldRetry(SQLException e) {
    String sqlState = e.getSQLState();
    if ("23000".equals(sqlState)) {
        // MySQL: Duplicate entry ... for key ...
        // Oracle: unique constraint ... violated
        // SQL Server: Violation of PRIMARY KEY constraint
        return true;
    }/*from w  w  w .j  a v a2s  .  co m*/
    if ("23001".equals(sqlState)) {
        // H2: Unique index or primary key violation
        return true;
    }
    if ("23505".equals(sqlState)) {
        // PostgreSQL: duplicate key value violates unique constraint
        return true;
    }
    if ("S0003".equals(sqlState) || "S0005".equals(sqlState)) {
        // SQL Server: Snapshot isolation transaction aborted due to update
        // conflict
        return true;
    }
    return false;
}

From source file:org.eclipse.ecr.core.storage.sql.LockManager.java

/**
 * Is the exception about a duplicate primary key?
 *//*from w  ww.java2 s .  c  o  m*/
protected boolean isDuplicateKeyException(SQLException e) {
    String sqlState = e.getSQLState();
    if ("23000".equals(sqlState)) {
        // MySQL: Duplicate entry ... for key ...
        // Oracle: unique constraint ... violated
        // SQL Server: Violation of PRIMARY KEY constraint
        return true;
    }
    if ("23001".equals(sqlState)) {
        // H2: Unique index or primary key violation
        return true;
    }
    if ("23505".equals(sqlState)) {
        // PostgreSQL: duplicate key value violates unique constraint
        return true;
    }
    return false;
}

From source file:broadwick.data.readers.DataFileReader.java

/**
 * Perform the insertion into the database.
 * @param connection      the connection to the database.
 * @param tableName       the name of the table into which the data will be put.
 * @param insertString    the command used to insert a row into the database.
 * @param dataFile        the [CSV] file that contained the data.
 * @param dateFormat      the format of the date in the file.
 * @param insertedColInfo a map of column name to column in the data file.
 * @param dateFields      a collection of columns in the csv file that contains date fields.
 * @return the number of rows inserted./*from ww  w. ja  v  a2 s.c om*/
 */
protected final int insert(final Connection connection, final String tableName, final String insertString,
        final String dataFile, final String dateFormat, final Map<String, Integer> insertedColInfo,
        final Collection<Integer> dateFields) {

    int inserted = 0;
    try {
        // Now do the insertion.
        log.trace("Inserting into {} via {}", tableName, insertString);
        PreparedStatement pstmt = connection.prepareStatement(insertString);
        log.trace("Prepared statement = {}", pstmt.toString());

        try (FileInput instance = new FileInput(dataFile, ",")) {
            final StopWatch sw = new StopWatch();
            sw.start();
            List<String> data = instance.readLine();
            while (data != null && !data.isEmpty()) {
                int parameterIndex = 1;
                for (Map.Entry<String, Integer> entry : insertedColInfo.entrySet()) {
                    if (entry.getValue() == -1) {
                        pstmt.setObject(parameterIndex, null);
                    } else {
                        final String value = data.get(entry.getValue() - 1);
                        if (dateFields.contains(entry.getValue())) {
                            int dateField = Integer.MAX_VALUE;
                            if (value != null && !value.isEmpty()) {
                                dateField = BroadwickConstants.getDate(value, dateFormat);
                            }
                            pstmt.setObject(parameterIndex, dateField);
                        } else {
                            pstmt.setObject(parameterIndex, value);
                        }
                    }
                    parameterIndex++;
                }
                pstmt.addBatch();
                try {
                    pstmt.executeUpdate();
                    inserted++;
                } catch (SQLException ex) {
                    if ("23505".equals(ex.getSQLState())) {
                        //Ignore found duplicate from database view
                        continue;
                    } else {
                        log.warn("Duplicate data found for {}: continuing despite errors: {}", data.get(0),
                                ex.getLocalizedMessage());
                        log.trace("{}", Throwables.getStackTraceAsString(ex));
                        throw ex;
                    }
                }
                if (inserted % 250000 == 0) {
                    log.trace("Inserted {} rows in {}", inserted, sw.toString());
                    connection.commit();
                    pstmt.close();
                    pstmt = connection.prepareStatement(insertString);
                }

                data = instance.readLine();
            }
            connection.commit();

        } catch (IOException ex) {
            log.error("IO error : {}", ex.getLocalizedMessage());
            log.trace("{}", Throwables.getStackTraceAsString(ex));
        } catch (SQLException ex) {
            log.error("SQL Error : {}", ex.getLocalizedMessage());
            log.trace("{}", Throwables.getStackTraceAsString(ex));
            throw ex;
        } finally {
            pstmt.close();
        }
    } catch (SQLException ex) {
        log.error("{}", ex.getLocalizedMessage());
        log.trace("{}", Throwables.getStackTraceAsString(ex));
        throw new BroadwickException(ex);
    }

    return inserted;
}

From source file:org.wso2.carbon.is.migration.MigrationDatabaseCreator.java

/**
 * executes given sql/* ww  w .  j  a  v  a2  s.  com*/
 *
 * @param sql
 * @throws Exception
 */
private void executeSQL(String sql) throws Exception {

    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;
    }

    ResultSet resultSet = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("SQL : " + sql);
        }

        boolean ret;
        int updateCount = 0, updateCountTotal = 0;
        ret = statement.execute(sql);
        updateCount = statement.getUpdateCount();
        resultSet = statement.getResultSet();
        do {
            if (!ret && updateCount != -1) {
                updateCountTotal += updateCount;
            }
            ret = statement.getMoreResults();
            if (ret) {
                updateCount = statement.getUpdateCount();
                resultSet = statement.getResultSet();
            }
        } while (ret);

        if (log.isDebugEnabled()) {
            log.debug(sql + " : " + updateCountTotal + " rows affected");
        }
        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            log.debug(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
    } catch (SQLException e) {
        if (e.getSQLState().equals("X0Y32") || e.getSQLState().equals("42710")) {
            // eliminating the table already exception for the derby and DB2 database types
            if (log.isDebugEnabled()) {
                log.info("Table Already Exists. Hence, skipping table creation");
            }
        } else {
            throw new Exception("Error occurred while executing : " + sql, e);
        }
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.error("Error occurred while closing result set.", e);
            }
        }
    }
}