Example usage for java.sql SQLWarning getNextWarning

List of usage examples for java.sql SQLWarning getNextWarning

Introduction

In this page you can find the example usage for java.sql SQLWarning getNextWarning.

Prototype

public SQLWarning getNextWarning() 

Source Link

Document

Retrieves the warning chained to this SQLWarning object by setNextWarning.

Usage

From source file:org.apache.bigtop.itest.hive.TestJdbc.java

@Test
public void preparedStmtAndResultSet() throws SQLException {
    final String tableName = "bigtop_jdbc_psars_test_table";
    try (Statement stmt = conn.createStatement()) {
        stmt.execute("drop table if exists " + tableName);
        stmt.execute("create table " + tableName + " (bo boolean, ti tinyint, db double, fl float, "
                + "i int, lo bigint, sh smallint, st varchar(32))");
    }/*from   w  w  w. ja v  a 2s . c om*/

    // NOTE Hive 1.2 theoretically support binary, Date & Timestamp in JDBC, but I get errors when I
    // try to put them in the query.
    try (PreparedStatement ps = conn
            .prepareStatement("insert into " + tableName + " values (?, ?, ?, ?, ?, ?, ?, ?)")) {
        ps.setBoolean(1, true);
        ps.setByte(2, (byte) 1);
        ps.setDouble(3, 3.141592654);
        ps.setFloat(4, 3.14f);
        ps.setInt(5, 3);
        ps.setLong(6, 10L);
        ps.setShort(7, (short) 20);
        ps.setString(8, "abc");
        ps.executeUpdate();
    }

    try (PreparedStatement ps = conn.prepareStatement("insert into " + tableName + " (i, st) " + "values(?, ?)",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
        ps.setNull(1, Types.INTEGER);
        ps.setObject(2, "mary had a little lamb");
        ps.executeUpdate();
        ps.setNull(1, Types.INTEGER, null);
        ps.setString(2, "its fleece was white as snow");
        ps.clearParameters();
        ps.setNull(1, Types.INTEGER, null);
        ps.setString(2, "its fleece was white as snow");
        ps.execute();

    }

    try (Statement stmt = conn.createStatement()) {

        ResultSet rs = stmt.executeQuery("select * from " + tableName);

        ResultSetMetaData md = rs.getMetaData();

        int colCnt = md.getColumnCount();
        LOG.debug("Column count is " + colCnt);

        for (int i = 1; i <= colCnt; i++) {
            LOG.debug("Looking at column " + i);
            String strrc = md.getColumnClassName(i);
            LOG.debug("Column class name is " + strrc);

            int intrc = md.getColumnDisplaySize(i);
            LOG.debug("Column display size is " + intrc);

            strrc = md.getColumnLabel(i);
            LOG.debug("Column label is " + strrc);

            strrc = md.getColumnName(i);
            LOG.debug("Column name is " + strrc);

            intrc = md.getColumnType(i);
            LOG.debug("Column type is " + intrc);

            strrc = md.getColumnTypeName(i);
            LOG.debug("Column type name is " + strrc);

            intrc = md.getPrecision(i);
            LOG.debug("Precision is " + intrc);

            intrc = md.getScale(i);
            LOG.debug("Scale is " + intrc);

            boolean boolrc = md.isAutoIncrement(i);
            LOG.debug("Is auto increment? " + boolrc);

            boolrc = md.isCaseSensitive(i);
            LOG.debug("Is case sensitive? " + boolrc);

            boolrc = md.isCurrency(i);
            LOG.debug("Is currency? " + boolrc);

            intrc = md.getScale(i);
            LOG.debug("Scale is " + intrc);

            intrc = md.isNullable(i);
            LOG.debug("Is nullable? " + intrc);

            boolrc = md.isReadOnly(i);
            LOG.debug("Is read only? " + boolrc);

        }

        while (rs.next()) {
            LOG.debug("bo = " + rs.getBoolean(1));
            LOG.debug("bo = " + rs.getBoolean("bo"));
            LOG.debug("ti = " + rs.getByte(2));
            LOG.debug("ti = " + rs.getByte("ti"));
            LOG.debug("db = " + rs.getDouble(3));
            LOG.debug("db = " + rs.getDouble("db"));
            LOG.debug("fl = " + rs.getFloat(4));
            LOG.debug("fl = " + rs.getFloat("fl"));
            LOG.debug("i = " + rs.getInt(5));
            LOG.debug("i = " + rs.getInt("i"));
            LOG.debug("lo = " + rs.getLong(6));
            LOG.debug("lo = " + rs.getLong("lo"));
            LOG.debug("sh = " + rs.getShort(7));
            LOG.debug("sh = " + rs.getShort("sh"));
            LOG.debug("st = " + rs.getString(8));
            LOG.debug("st = " + rs.getString("st"));
            LOG.debug("tm = " + rs.getObject(8));
            LOG.debug("tm = " + rs.getObject("st"));
            LOG.debug("tm was null " + rs.wasNull());
        }
        LOG.debug("bo is column " + rs.findColumn("bo"));

        int intrc = rs.getConcurrency();
        LOG.debug("concurrency " + intrc);

        intrc = rs.getFetchDirection();
        LOG.debug("fetch direction " + intrc);

        intrc = rs.getType();
        LOG.debug("type " + intrc);

        Statement copy = rs.getStatement();

        SQLWarning warning = rs.getWarnings();
        while (warning != null) {
            LOG.debug("Found a warning: " + warning.getMessage());
            warning = warning.getNextWarning();
        }
        rs.clearWarnings();
    }
}

From source file:org.springframework.batch.item.database.AbstractCursorItemReader.java

/**
 * Throw a SQLWarningException if we're not ignoring warnings, else log the
 * warnings (at debug level)./*  w w w  . j a  v  a 2s  . co  m*/
 *
 * @param statement the current statement to obtain the warnings from, if there are any.
 * @throws SQLException if interaction with provided statement fails.
 *
 * @see org.springframework.jdbc.SQLWarningException
 */
protected void handleWarnings(Statement statement) throws SQLWarningException, SQLException {
    if (ignoreWarnings) {
        if (log.isDebugEnabled()) {
            SQLWarning warningToLog = statement.getWarnings();
            while (warningToLog != null) {
                log.debug("SQLWarning ignored: SQL state '" + warningToLog.getSQLState() + "', error code '"
                        + warningToLog.getErrorCode() + "', message [" + warningToLog.getMessage() + "]");
                warningToLog = warningToLog.getNextWarning();
            }
        }
    } else {
        SQLWarning warnings = statement.getWarnings();
        if (warnings != null) {
            throw new SQLWarningException("Warning not ignored", warnings);
        }
    }
}

From source file:org.codehaus.mojo.dbupgrade.sqlexec.DefaultSQLExec.java

/**
 * Exec the sql statement./* ww w .  ja v a2 s .  c  o m*/
 */
private void execSQL(String sql, PrintStream out) throws SQLException {
    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;
    }

    if (config.isVerbose()) {
        out.append(sql).append("\n");
    }

    ResultSet resultSet = null;
    try {
        totalStatements++;

        boolean ret;
        int updateCount, updateCountTotal = 0;

        ret = statement.execute(sql);
        updateCount = statement.getUpdateCount();
        resultSet = statement.getResultSet();
        do {
            if (!ret) {
                if (updateCount != -1) {
                    updateCountTotal += updateCount;
                }
            } else {
                if (config.isPrintResultSet()) {
                    printResultSet(resultSet, out);
                }
            }
            ret = statement.getMoreResults();
            if (ret) {
                updateCount = statement.getUpdateCount();
                resultSet = statement.getResultSet();
            }
        } while (ret);

        if (config.isPrintResultSet()) {
            StringBuffer line = new StringBuffer();
            line.append(updateCountTotal).append(" rows affected");
            out.println(line);
        }

        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
        successfulStatements++;
    } catch (SQLException e) {
        if (SQLExecConfig.ON_ERROR_ABORT.equalsIgnoreCase(config.getOnError())) {
            throw new SQLException("Unable to execute: " + sql, e);
        }
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
}

From source file:org.sakaiproject.util.conversion.SchemaConversionController.java

public boolean migrate(DataSource datasource, SchemaConversionHandler convert, SchemaConversionDriver driver)
        throws SchemaConversionException {
    // issues:/*from w ww.j av  a 2s . c o m*/
    // Data size bigger than max size for this type?
    // Failure may cause rest of set to fail?

    boolean alldone = false;
    Connection connection = null;
    PreparedStatement selectNextBatch = null;
    PreparedStatement markNextBatch = null;
    PreparedStatement completeNextBatch = null;
    PreparedStatement selectRecord = null;
    PreparedStatement selectValidateRecord = null;
    PreparedStatement updateRecord = null;
    PreparedStatement reportError = null;
    ResultSet rs = null;
    try {
        connection = datasource.getConnection();
        connection.setAutoCommit(false);
        selectNextBatch = connection.prepareStatement(driver.getSelectNextBatch());
        markNextBatch = connection.prepareStatement(driver.getMarkNextBatch());
        completeNextBatch = connection.prepareStatement(driver.getCompleteNextBatch());
        String selectRecordStr = driver.getSelectRecord();
        selectRecord = connection.prepareStatement(selectRecordStr);
        selectValidateRecord = connection.prepareStatement(driver.getSelectValidateRecord());
        updateRecord = connection.prepareStatement(driver.getUpdateRecord());
        if (reportErrorsInTable) {
            reportError = connection.prepareStatement(driver.getErrorReportSql());
        }
        // log.info("  +++ updateRecord == " + driver.getUpdateRecord());

        // 2. select x at a time
        rs = selectNextBatch.executeQuery();
        List<String> l = new ArrayList<String>();
        while (rs.next()) {
            l.add(rs.getString(1));
        }
        rs.close();
        log.info("Migrating " + l.size() + " records of " + nrecords);

        for (String id : l) {

            markNextBatch.clearParameters();
            markNextBatch.clearWarnings();
            markNextBatch.setString(1, id);
            if (markNextBatch.executeUpdate() != 1) {
                log.warn("  --> Failed to mark id [" + id + "][" + id.length() + "] for processing ");
                insertErrorReport(reportError, id, driver.getHandler(),
                        "Unable to mark this record for processing");
            }
        }

        int count = 1;
        for (String id : l) {
            selectRecord.clearParameters();
            selectRecord.setString(1, id);
            rs = selectRecord.executeQuery();
            Object source = null;
            if (rs.next()) {
                source = convert.getSource(id, rs);
            } else {
                log.warn("  --> Result-set is empty for id: " + id + " [" + count + " of " + l.size() + "]");
                insertErrorReport(reportError, id, driver.getHandler(), "Result set empty getting source");
            }
            rs.close();
            if (source == null) {
                log.warn("  --> Source is null for id: " + id + " [" + count + " of " + l.size() + "]");
                insertErrorReport(reportError, id, driver.getHandler(), "Source null");
            } else {
                try {
                    updateRecord.clearParameters();
                    if (convert.convertSource(id, source, updateRecord)) {
                        if (updateRecord.executeUpdate() == 1) {
                            selectValidateRecord.clearParameters();
                            selectValidateRecord.setString(1, id);
                            rs = selectValidateRecord.executeQuery();
                            Object result = null;
                            if (rs.next()) {
                                result = convert.getValidateSource(id, rs);
                            }

                            convert.validate(id, source, result);
                        } else {
                            log.warn("  --> Failed to update record " + id + " [" + count + " of " + l.size()
                                    + "]");
                            insertErrorReport(reportError, id, driver.getHandler(), "Failed to update record");
                        }
                    } else {
                        log.warn("  --> Did not update record " + id + " [" + count + " of " + l.size() + "]");
                        insertErrorReport(reportError, id, driver.getHandler(), "Failed to write update to db");
                    }
                    rs.close();
                } catch (SQLException e) {
                    String msg = "  --> Failure converting or validating item " + id + " [" + count + " of "
                            + l.size() + "] \n";
                    insertErrorReport(reportError, id, driver.getHandler(),
                            "Exception while updating, converting or verifying item");
                    SQLWarning warnings = updateRecord.getWarnings();
                    while (warnings != null) {
                        msg += "\t\t\t" + warnings.getErrorCode() + "\t" + warnings.getMessage() + "\n";
                        warnings = warnings.getNextWarning();
                    }
                    log.warn(msg, e);
                    updateRecord.clearWarnings();
                    updateRecord.clearParameters();
                }

            }
            completeNextBatch.clearParameters();
            completeNextBatch.setString(1, id);
            if (completeNextBatch.executeUpdate() != 1) {
                log.warn("  --> Failed to mark id " + id + " for processing [" + count + " of " + l.size()
                        + "]");
                insertErrorReport(reportError, id, driver.getHandler(), "Unable to complete next batch");
            }
            count++;
        }

        if (l.size() == 0) {
            dropRegisterTable(connection, convert, driver);
            alldone = true;
        }
        connection.commit();
        nrecords -= l.size();

    } catch (Exception e) {
        log.error("Failed to perform migration ", e);
        try {
            connection.rollback();
            log.error("  ==> Rollback Sucessful ", e);
        } catch (Exception ex) {
            log.error("  ==> Rollback Failed ", e);
        }
        throw new SchemaConversionException(
                "Schema Conversion has been aborted due to earlier errors, please investigate ");

    } finally {
        try {
            rs.close();
        } catch (Exception ex) {
            log.debug("exception closing rs " + ex);
        }
        try {
            selectNextBatch.close();
        } catch (Exception ex) {
            log.debug("exception closing selectNextBatch " + ex);
        }
        try {
            markNextBatch.close();
        } catch (Exception ex) {
            log.debug("exception closing markNextBatch " + ex);
        }
        try {
            completeNextBatch.close();
        } catch (Exception ex) {
            log.debug("exception closing completeNextBatch " + ex);
        }
        try {
            selectRecord.close();
        } catch (Exception ex) {
            log.debug("exception closing selectRecord " + ex);
        }
        try {
            selectValidateRecord.close();
        } catch (Exception ex) {
            log.debug("exception closing selectValidateRecord " + ex);
        }
        try {
            updateRecord.close();
        } catch (Exception ex) {
            log.debug("exception closing updateRecord " + ex);
        }
        if (reportError != null) {
            try {
                reportError.close();
            } catch (Exception ex) {
                log.debug("exception closing reportError " + ex);
            }
        }

        try {
            connection.close();

        } catch (Exception ex) {
            log.debug("Exception closing connection " + ex);
        }

    }
    return !alldone;
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * executes given sql/*from w w w  .ja  va  2  s  .  c  o  m*/
 *
 * @param sql Sql query to be executed
 * @throws DashboardPortalException
 */
private void executeQuery(String sql) throws DashboardPortalException {
    // Check and ignore empty statements
    if (sql.trim().isEmpty()) {
        return;
    }
    ResultSet resultSet = null;
    Connection conn = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("SQL : " + sql);
        }
        boolean ret;
        int updateCount, updateCountTotal = 0;
        ret = statement.execute(sql);
        updateCount = statement.getUpdateCount();
        resultSet = statement.getResultSet();
        do {
            if (!ret) {
                if (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");
        }
        conn = dataSource.getConnection();
        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            if (log.isDebugEnabled()) {
                log.debug(warning + " sql warning");
                warning = warning.getNextWarning();
            }
        }
        conn.clearWarnings();
    } catch (SQLException e) {
        throw new DashboardPortalException("Error occurred while executing : " + sql, e);
    } finally {
        closeDatabaseResources(conn, null, resultSet);
    }
}

From source file:org.apache.torque.task.TorqueSQLExec.java

/**
 * Exec the sql statement./*from  w  w w.j a v a 2  s .co  m*/
 *
 * @param sql
 * @param out
 * @throws SQLException
 */
protected void execSQL(String sql, PrintStream out) throws SQLException {
    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;
    }

    try {
        totalSql++;
        if (!statement.execute(sql)) {
            log(statement.getUpdateCount() + " rows affected", Project.MSG_VERBOSE);
        } else {
            if (print) {
                printResults(out);
            }
        }

        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            log(warning + " sql warning", Project.MSG_VERBOSE);
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
        goodSql++;
    } catch (SQLException e) {
        System.out.println("Failed to execute: " + sql);
        if (!onError.equals("continue")) {
            throw e;
        }
        log(e.toString(), Project.MSG_ERR);
    }
}

From source file:org.gbif.ipt.service.manage.impl.SourceManagerImpl.java

private Connection getDbConnection(SqlSource source) throws SQLException {
    Connection conn = null;//w  w  w .  jav  a2  s.c  o m
    // try to connect to db via simple JDBC
    if (source.getHost() != null && source.getJdbcUrl() != null && source.getJdbcDriver() != null) {
        try {
            DriverManager.setLoginTimeout(CONNECTION_TIMEOUT_SECS);
            Class.forName(source.getJdbcDriver());
            conn = DriverManager.getConnection(source.getJdbcUrl(), source.getUsername(), source.getPassword());

            // If a SQLWarning object is available, log its
            // warning(s). There may be multiple warnings chained.

            SQLWarning warn = conn.getWarnings();
            while (warn != null) {
                log.warn("SQLWarning: state=" + warn.getSQLState() + ", message=" + warn.getMessage()
                        + ", vendor=" + warn.getErrorCode());
                warn = warn.getNextWarning();
            }
        } catch (java.lang.ClassNotFoundException e) {
            String msg = String.format(
                    "Couldnt load JDBC driver to create new external datasource connection with JDBC Class=%s and URL=%s. Error: %s",
                    source.getJdbcDriver(), source.getJdbcUrl(), e.getMessage());
            log.warn(msg, e);
            throw new SQLException(msg, e);
        } catch (Exception e) {
            String msg = String.format(
                    "Couldnt create new external datasource connection with JDBC Class=%s, URL=%s, user=%s. Error: %s",
                    source.getJdbcDriver(), source.getJdbcUrl(), source.getUsername(), e.getMessage());
            log.warn(msg, e);
            throw new SQLException(msg);
        }
    }
    return conn;
}

From source file:edu.lternet.pasta.token.TokenManager.java

/**
 * Returns a connection to the database.
 *
 * @return The database Connection object.
 *//*from  w ww. j av  a 2  s  . c  o  m*/
private Connection getConnection() throws ClassNotFoundException {

    Connection conn = null;

    SQLWarning warn;

    // Load the jdbc driver.
    try {
        Class.forName(this.dbDriver);
    } catch (ClassNotFoundException e) {
        logger.error("Can't load driver " + e.getMessage());
        throw (e);
    }

    // Make the database connection
    try {
        conn = DriverManager.getConnection(this.dbURL, this.dbUser, this.dbPassword);

        // If a SQLWarning object is available, print its warning(s).
        // There may be multiple warnings chained.
        warn = conn.getWarnings();

        if (warn != null) {
            while (warn != null) {
                logger.warn("SQLState: " + warn.getSQLState());
                logger.warn("Message:  " + warn.getMessage());
                logger.warn("Vendor: " + warn.getErrorCode());
                warn = warn.getNextWarning();
            }
        }
    } catch (SQLException e) {
        logger.error("Database access failed " + e);
    }

    return conn;

}

From source file:nl.nn.adapterframework.util.JdbcUtil.java

public static XmlBuilder warningsToXmlBuilder(SQLWarning warnings) {
    if (warnings != null) {
        XmlBuilder warningsElem = new XmlBuilder("warnings");
        while (warnings != null) {
            XmlBuilder warningElem = new XmlBuilder("warning");
            warningElem.addAttribute("errorCode", "" + warnings.getErrorCode());
            warningElem.addAttribute("sqlState", "" + warnings.getSQLState());
            String message = warnings.getMessage();

            // getCause() geeft unresolvedCompilationProblem (bij Peter Leeuwenburgh?)
            Throwable cause = warnings.getCause();
            if (cause != null) {
                warningElem.addAttribute("cause", cause.getClass().getName());
                if (message == null) {
                    message = cause.getMessage();
                } else {
                    message = message + ": " + cause.getMessage();
                }/*ww w . ja v  a  2  s. c  om*/
            }

            warningElem.addAttribute("message", message);
            warningsElem.addSubElement(warningElem);
            warnings = warnings.getNextWarning();
        }
        return warningsElem;
    }
    return null;
}

From source file:org.codehaus.mojo.sql.SqlExecMojo.java

/**
 * Exec the sql statement./* www  .  ja v a  2  s .  c o m*/
 * 
 * @param sql query to execute 
 * @param out the outputstream
 */
private void execSQL(String sql, PrintStream out) throws SQLException {
    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;
    }

    ResultSet resultSet = null;
    try {
        totalStatements++;
        getLog().debug("SQL: " + sql);

        boolean ret;
        int updateCountTotal = 0;

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

        getLog().debug(updateCountTotal + " rows affected");

        if (printResultSet) {
            StringBuffer line = new StringBuffer();
            line.append(updateCountTotal).append(" rows affected");
            out.println(line);
        }

        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            getLog().debug(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
        successfulStatements++;
    } catch (SQLException e) {
        getLog().error("Failed to execute: " + sql);
        if (ON_ERROR_ABORT.equalsIgnoreCase(getOnError())) {
            throw e;
        }
        getLog().error(e.toString());
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
}