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:com.espertech.esperio.db.core.MultiKeyMultiValueTable.java

private void runInsert(Connection connection, String query, Object[] keys, Object[] values) {
    PreparedStatement statement = null;
    try {/* www.  jav  a 2 s .co  m*/
        if ((ExecutionPathDebugLog.isDebugEnabled) && (log.isDebugEnabled())) {
            log.debug("Executing query '" + query + "' for keys '" + print(keys) + "'");
        }
        statement = connection.prepareStatement(query);
        int index = 1;
        for (Object key : keys) {
            statement.setObject(index, key);
            index++;
        }
        for (Object value : values) {
            statement.setObject(index, value);
            index++;
        }
        statement.executeUpdate();
    } catch (SQLException ex) {
        String message = "Failed to invoke : " + query + " :" + ex.getMessage();
        if ((ex.getSQLState() != null) && (ex.getSQLState().equals("23000"))) {
            throw new StoreExceptionDBDuplicateRow(message, ex);
        }
        log.error(message, ex);
        storeExceptionHandler.handle(message, ex);
        throw new StoreExceptionDBRel(message, ex);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
        }
    }
}

From source file:it.geosolutions.geobatch.destination.ingestion.OriginalArcsIngestionProcess.java

/**
 * @param dataStore/*from   w  w w. j a  v  a 2  s  .  co  m*/
 * @param outName2
 * @throws SQLException 
 * @throws IOException 
 */
private void createOutputFeature(DataStore dataStore, String featureName) throws IOException {
    try {
        DbUtils.dropFeatureType(dataStore, featureName);
    } catch (SQLException e) {
        // check for "table does not exist" error and ignore it
        if (!e.getSQLState().equals("42P01")) {
            throw new IOException(e);
        }
    }
    try {
        SimpleFeatureType featureType = DataUtilities.createType(featureName, readModel("roads_input_model"));
        dataStore.createSchema(featureType);
    } catch (SchemaException e) {
        throw new IOException(e);
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.DSWDatasourceServiceImpl.java

private IPentahoResultSet executeQuery(String connectionName, String query, String previewLimit)
        throws QueryValidationException {
    SQLConnection sqlConnection = null;/*from w ww .  j  a  va  2s .  c o m*/
    try {
        int limit = (previewLimit != null && previewLimit.length() > 0) ? Integer.parseInt(previewLimit) : -1;
        sqlConnection = (SQLConnection) PentahoConnectionFactory.getConnection(
                IPentahoConnection.SQL_DATASOURCE, connectionName, PentahoSessionHolder.getSession(),
                new SimpleLogger(DatasourceServiceHelper.class.getName()));
        sqlConnection.setMaxRows(limit);
        sqlConnection.setReadOnly(true);
        return sqlConnection.executeQuery(BEFORE_QUERY + query + AFTER_QUERY);
    } catch (SQLException e) {
        String error = "DatasourceServiceImpl.ERROR_0009_QUERY_VALIDATION_FAILED";
        if (e.getSQLState().equals("S0021")) { // Column already exists
            error = "DatasourceServiceImpl.ERROR_0021_DUPLICATE_COLUMN_NAMES";
        }
        logger.error(Messages.getErrorString(error));
        throw new QueryValidationException(Messages.getString(error));
    } catch (Exception e) {
        logger.error(Messages.getErrorString("DatasourceServiceImpl.ERROR_0009_QUERY_VALIDATION_FAILED", //$NON-NLS-1$
                e.getLocalizedMessage()), e);
        throw new QueryValidationException(e.getLocalizedMessage(), e);
    } finally {
        if (sqlConnection != null) {
            sqlConnection.close();
        }
    }
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleFsPersistenceManager.java

/**
 * logs an sql exception//from  ww w .  ja v a 2 s .  co m
 * @param message
 * @param se
 */
protected void logException(String message, SQLException se) {
    if (message != null) {
        BundleFsPersistenceManager.log.error(message);
    }
    BundleFsPersistenceManager.log.error("       Reason: " + se.getMessage());
    BundleFsPersistenceManager.log.error("   State/Code: " + se.getSQLState() + "/" + se.getErrorCode());
    BundleFsPersistenceManager.log.debug("   dump:", se);
}

From source file:org.dbmaintain.DefaultDbMaintainer.java

protected String getErrorMessage(Script script, DbMaintainException e) {
    String exceptionMessage = e.getMessage();
    Throwable cause = e.getCause();
    if (cause != null) {
        exceptionMessage += "\n\nCaused by: " + cause.getMessage();
        if (cause instanceof SQLException) {
            SQLException sqlException = (SQLException) cause;
            if (!exceptionMessage.endsWith("\n")) {
                exceptionMessage += "\n";
            }//w  w  w.  java  2s .  c o m
            exceptionMessage += "Error code: " + sqlException.getErrorCode() + ", sql state: "
                    + sqlException.getSQLState();
        }
    }

    String message = "\nError while executing script " + script.getFileName() + ": " + exceptionMessage
            + "\n\n";
    message += "A rollback was performed but there could still be changes that were committed in the database (for example a creation of a table).\n"
            + getErrorScriptOptionsMessage(script) + "\n\n";
    if (maxNrOfCharsWhenLoggingScriptContent > 0) {
        String scriptContents = script.getScriptContentHandle()
                .getScriptContentsAsString(maxNrOfCharsWhenLoggingScriptContent);
        message += "Full contents of failed script " + script.getFileName() + ":\n";
        message += "----------------------------------------------------\n";
        message += scriptContents + "\n";
        message += "----------------------------------------------------\n";
    }
    return message;
}

From source file:com.migratebird.DefaultDbUpdate.java

protected String getErrorMessage(Script script, MigrateBirdException e) {
    String exceptionMessage = e.getMessage();
    Throwable cause = e.getCause();
    if (cause != null) {
        exceptionMessage += "\n\nCaused by: " + cause.getMessage();
        if (cause instanceof SQLException) {
            SQLException sqlException = (SQLException) cause;
            if (!exceptionMessage.endsWith("\n")) {
                exceptionMessage += "\n";
            }//from  w  ww  . j  a  v a 2s  .  c  o m
            exceptionMessage += "Error code: " + sqlException.getErrorCode() + ", sql state: "
                    + sqlException.getSQLState();
        }
    }

    String message = "\nError while executing script " + script.getFileName() + ": " + exceptionMessage
            + "\n\n";
    message += "A rollback was performed but there could still be changes that were committed in the database (for example a creation of a table).\n"
            + getErrorScriptOptionsMessage(script) + "\n\n";
    if (maxNrOfCharsWhenLoggingScriptContent > 0) {
        String scriptContents = script.getScriptContentHandle()
                .getScriptContentsAsString(maxNrOfCharsWhenLoggingScriptContent);
        message += "Full contents of failed script " + script.getFileName() + ":\n";
        message += "----------------------------------------------------\n";
        message += scriptContents + "\n";
        message += "----------------------------------------------------\n";
    }
    return message;
}

From source file:au.edu.jcu.fascinator.plugin.harvester.directory.DerbyCache.java

/**
 * Shutdown the database connections and cleanup.
 * /*w  w w  .  j av a 2s.  c  o m*/
 * @throws Exception if there are errors
 */
public void shutdown() throws Exception {
    // Derby can only be shutdown from one thread,
    // we'll catch errors from the rest.
    // String threadedShutdownMessage = DERBY_DRIVER
    // + " is not registered with the JDBC driver manager";
    try {
        // Tell the database to close
        // DriverManager.getConnection(DERBY_PROTOCOL + ";shutdown=true");
        // Shutdown just this database (but not the engine)
        DriverManager.getConnection(DERBY_PROTOCOL + DATABASE_NAME + ";shutdown=true");
    } catch (SQLException ex) {
        // These test values are used if the engine is NOT shutdown
        if (ex.getErrorCode() == 45000 && ex.getSQLState().equals("08006")) {

            // Valid response
            // if (ex.getErrorCode() == 50000 &&
            // ex.getSQLState().equals("XJ015")) {
            // Error response
        } else {
            // Make sure we ignore simple thread issues
            // if (!ex.getMessage().equals(threadedShutdownMessage)) {
            // throw new Exception("Error during database shutdown:", ex);
            // }
        }
    } finally {
        try {
            // Close our connection
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (SQLException ex) {
            throw new Exception("Error closing connection:", ex);
        }
    }
}

From source file:org.apache.jmeter.protocol.jdbc.sampler.JDBCSampler.java

public SampleResult sample(Entry e) {
    log.debug("sampling jdbc");

    SampleResult res = new SampleResult();
    res.setSampleLabel(getName());//from   w w  w .  j a v  a 2 s . co  m
    res.setSamplerData(toString());
    res.setDataType(SampleResult.TEXT);
    res.setContentType("text/plain"); // $NON-NLS-1$
    res.setDataEncoding(ENCODING);

    // Assume we will be successful
    res.setSuccessful(true);
    res.setResponseMessageOK();
    res.setResponseCodeOK();

    res.sampleStart();
    Connection conn = null;
    Statement stmt = null;

    try {

        try {
            conn = DataSourceElement.getConnection(getDataSource());
        } finally {
            res.latencyEnd(); // use latency to measure connection time
        }
        res.setResponseHeaders(conn.toString());

        // Based on query return value, get results
        String _queryType = getQueryType();
        if (SELECT.equals(_queryType)) {
            stmt = conn.createStatement();
            ResultSet rs = null;
            try {
                rs = stmt.executeQuery(getQuery());
                res.setResponseData(getStringFromResultSet(rs).getBytes(ENCODING));
            } finally {
                close(rs);
            }
        } else if (CALLABLE.equals(_queryType)) {
            CallableStatement cstmt = getCallableStatement(conn);
            int out[] = setArguments(cstmt);
            // A CallableStatement can return more than 1 ResultSets
            // plus a number of update counts.
            boolean hasResultSet = cstmt.execute();
            String sb = resultSetsToString(cstmt, hasResultSet, out);
            res.setResponseData(sb.getBytes(ENCODING));
        } else if (UPDATE.equals(_queryType)) {
            stmt = conn.createStatement();
            stmt.executeUpdate(getQuery());
            int updateCount = stmt.getUpdateCount();
            String results = updateCount + " updates";
            res.setResponseData(results.getBytes(ENCODING));
        } else if (PREPARED_SELECT.equals(_queryType)) {
            PreparedStatement pstmt = getPreparedStatement(conn);
            setArguments(pstmt);
            pstmt.executeQuery();
            String sb = resultSetsToString(pstmt, true, null);
            res.setResponseData(sb.getBytes(ENCODING));
        } else if (PREPARED_UPDATE.equals(_queryType)) {
            PreparedStatement pstmt = getPreparedStatement(conn);
            setArguments(pstmt);
            pstmt.executeUpdate();
            String sb = resultSetsToString(pstmt, false, null);
            res.setResponseData(sb.getBytes(ENCODING));
        } else if (ROLLBACK.equals(_queryType)) {
            conn.rollback();
            res.setResponseData(ROLLBACK.getBytes(ENCODING));
        } else if (COMMIT.equals(_queryType)) {
            conn.commit();
            res.setResponseData(COMMIT.getBytes(ENCODING));
        } else if (AUTOCOMMIT_FALSE.equals(_queryType)) {
            conn.setAutoCommit(false);
            res.setResponseData(AUTOCOMMIT_FALSE.getBytes(ENCODING));
        } else if (AUTOCOMMIT_TRUE.equals(_queryType)) {
            conn.setAutoCommit(true);
            res.setResponseData(AUTOCOMMIT_TRUE.getBytes(ENCODING));
        } else { // User provided incorrect query type
            String results = "Unexpected query type: " + _queryType;
            res.setResponseMessage(results);
            res.setSuccessful(false);
        }

    } catch (SQLException ex) {
        final String errCode = Integer.toString(ex.getErrorCode());
        res.setResponseMessage(ex.toString());
        res.setResponseCode(ex.getSQLState() + " " + errCode);
        res.setSuccessful(false);
    } catch (UnsupportedEncodingException ex) {
        res.setResponseMessage(ex.toString());
        res.setResponseCode("000"); // TODO - is this correct?
        res.setSuccessful(false);
    } catch (IOException ex) {
        res.setResponseMessage(ex.toString());
        res.setResponseCode("000"); // TODO - is this correct?
        res.setSuccessful(false);
    } finally {
        close(stmt);
        close(conn);
    }

    // TODO: process warnings? Set Code and Message to success?
    res.sampleEnd();
    return res;
}

From source file:org.batoo.jpa.core.impl.jdbc.dbutils.AbstractQueryRunner.java

/**
 * Throws a new exception with a more informative error message.
 * // w  w  w  . ja v a 2  s.  c  om
 * @param cause
 *            The original exception that will be chained to the new exception when it's rethrown.
 * 
 * @param sql
 *            The query that was executing when the exception happened.
 * 
 * @param params
 *            The query replacement parameters; <code>null</code> is a valid value to pass in.
 * 
 * @throws SQLException
 *             if a database access error occurs
 */
protected void rethrow(SQLException cause, String sql, Object... params) throws SQLException {

    String causeMessage = cause.getMessage();
    if (causeMessage == null) {
        causeMessage = "";
    }
    final StringBuffer msg = new StringBuffer(causeMessage);

    msg.append(" Query: ");
    msg.append(sql);
    msg.append(" Parameters: ");

    if (params == null) {
        msg.append("[]");
    } else {
        msg.append(Arrays.deepToString(params));
    }

    final SQLException e = new SQLException(msg.toString(), cause.getSQLState(), cause.getErrorCode());
    e.setNextException(cause);

    throw e;
}

From source file:org.sonar.db.AbstractDbTester.java

public void executeUpdateSql(String sql, Object... params) {
    try (Connection connection = getConnection()) {
        new QueryRunner().update(connection, sql, params);
        if (!connection.getAutoCommit()) {
            connection.commit();//w  w  w . j av a2s .  c  o  m
        }
    } catch (SQLException e) {
        SQLException nextException = e.getNextException();
        if (nextException != null) {
            throw new IllegalStateException("Fail to execute sql: " + sql, new SQLException(e.getMessage(),
                    nextException.getSQLState(), nextException.getErrorCode(), nextException));
        }
        throw new IllegalStateException("Fail to execute sql: " + sql, e);
    } catch (Exception e) {
        throw new IllegalStateException("Fail to execute sql: " + sql, e);
    }
}