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

private static void checkForWarning(SQLWarning warn) throws SQLException {

    // If a SQLWarning object was given, display the
    // warning messages.  Note that there could be
    // multiple warnings chained together

    if (warn != null) {
        System.out.println("*** Warning ***\n");
        while (warn != null) {
            System.out.println("SQLState: " + warn.getSQLState());
            System.out.println("Message:  " + warn.getMessage());
            System.out.println("Vendor:   " + warn.getErrorCode());
            System.out.println("");
            warn = warn.getNextWarning();
        }// w w w  .java2s .c  o  m
    }
}

From source file:com.oracle.tutorial.jdbc.JDBCTutorialUtilities.java

public static void printWarnings(SQLWarning warning) throws SQLException {
    if (warning != null) {
        System.out.println("\n---Warning---\n");
        while (warning != null) {
            System.out.println("Message: " + warning.getMessage());
            System.out.println("SQLState: " + warning.getSQLState());
            System.out.print("Vendor error code: ");
            System.out.println(warning.getErrorCode());
            System.out.println("");
            warning = warning.getNextWarning();
        }/*from www. j  av a 2s  .  c  om*/
    }
}

From source file:com.xqdev.sql.MLSQL.java

private static void addWarnings(Element meta, SQLWarning w) {
    if (w == null)
        return;/*from w  w  w  . jav  a  2  s . co m*/

    Namespace sql = meta.getNamespace();
    Element warnings = new Element("warnings", sql);
    meta.addContent(warnings);
    do {
        warnings.addContent(new Element("warning", sql).setAttribute("type", w.getClass().getName())
                .addContent(new Element("reason", sql).setText(w.getMessage()))
                .addContent(new Element("sql-state", sql).setText(w.getSQLState()))
                .addContent(new Element("vendor-code", sql).setText("" + w.getErrorCode())));
        w = w.getNextWarning();
    } while (w != null);
}

From source file:org.springframework.jdbc.datasource.init.ScriptUtils.java

/**
 * Execute the given SQL script.//w ww  . j  a va 2  s. c  o  m
 * <p>Statement separators and comments will be removed before executing
 * individual statements within the supplied script.
 * <p><strong>Warning</strong>: this method does <em>not</em> release the
 * provided {@link Connection}.
 * @param connection the JDBC connection to use to execute the script; already
 * configured and ready to use
 * @param resource the resource (potentially associated with a specific encoding)
 * to load the SQL script from
 * @param continueOnError whether or not to continue without throwing an exception
 * in the event of an error
 * @param ignoreFailedDrops whether or not to continue in the event of specifically
 * an error on a {@code DROP} statement
 * @param commentPrefix the prefix that identifies single-line comments in the
 * SQL script &mdash; typically "--"
 * @param separator the script statement separator; defaults to
 * {@value #DEFAULT_STATEMENT_SEPARATOR} if not specified and falls back to
 * {@value #FALLBACK_STATEMENT_SEPARATOR} as a last resort; may be set to
 * {@value #EOF_STATEMENT_SEPARATOR} to signal that the script contains a
 * single statement without a separator
 * @param blockCommentStartDelimiter the <em>start</em> block comment delimiter; never
 * {@code null} or empty
 * @param blockCommentEndDelimiter the <em>end</em> block comment delimiter; never
 * {@code null} or empty
 * @throws ScriptException if an error occurred while executing the SQL script
 * @see #DEFAULT_STATEMENT_SEPARATOR
 * @see #FALLBACK_STATEMENT_SEPARATOR
 * @see #EOF_STATEMENT_SEPARATOR
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection
 * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
 */
public static void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError,
        boolean ignoreFailedDrops, String commentPrefix, @Nullable String separator,
        String blockCommentStartDelimiter, String blockCommentEndDelimiter) throws ScriptException {

    try {
        if (logger.isInfoEnabled()) {
            logger.info("Executing SQL script from " + resource);
        }
        long startTime = System.currentTimeMillis();

        String script;
        try {
            script = readScript(resource, commentPrefix, separator);
        } catch (IOException ex) {
            throw new CannotReadScriptException(resource, ex);
        }

        if (separator == null) {
            separator = DEFAULT_STATEMENT_SEPARATOR;
        }
        if (!EOF_STATEMENT_SEPARATOR.equals(separator) && !containsSqlScriptDelimiters(script, separator)) {
            separator = FALLBACK_STATEMENT_SEPARATOR;
        }

        List<String> statements = new LinkedList<>();
        splitSqlScript(resource, script, separator, commentPrefix, blockCommentStartDelimiter,
                blockCommentEndDelimiter, statements);

        int stmtNumber = 0;
        Statement stmt = connection.createStatement();
        try {
            for (String statement : statements) {
                stmtNumber++;
                try {
                    stmt.execute(statement);
                    int rowsAffected = stmt.getUpdateCount();
                    if (logger.isDebugEnabled()) {
                        logger.debug(rowsAffected + " returned as update count for SQL: " + statement);
                        SQLWarning warningToLog = stmt.getWarnings();
                        while (warningToLog != null) {
                            logger.debug("SQLWarning ignored: SQL state '" + warningToLog.getSQLState()
                                    + "', error code '" + warningToLog.getErrorCode() + "', message ["
                                    + warningToLog.getMessage() + "]");
                            warningToLog = warningToLog.getNextWarning();
                        }
                    }
                } catch (SQLException ex) {
                    boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
                    if (continueOnError || (dropStatement && ignoreFailedDrops)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(ScriptStatementFailedException.buildErrorMessage(statement, stmtNumber,
                                    resource), ex);
                        }
                    } else {
                        throw new ScriptStatementFailedException(statement, stmtNumber, resource, ex);
                    }
                }
            }
        } finally {
            try {
                stmt.close();
            } catch (Throwable ex) {
                logger.debug("Could not close JDBC Statement", ex);
            }
        }

        long elapsedTime = System.currentTimeMillis() - startTime;
        if (logger.isInfoEnabled()) {
            logger.info("Executed SQL script from " + resource + " in " + elapsedTime + " ms.");
        }
    } catch (Exception ex) {
        if (ex instanceof ScriptException) {
            throw (ScriptException) ex;
        }
        throw new UncategorizedScriptException(
                "Failed to execute database script from resource [" + resource + "]", ex);
    }
}

From source file:edu.lternet.pasta.doi.DOIScannerTest.java

private static Connection getConnection() throws Exception {
    Connection conn = null;/*from   ww w .j  a v  a  2s .c om*/
    SQLWarning warn;

    Class.forName(dbDriver);

    // Make the database connection
    conn = DriverManager.getConnection(dbUrl, dbUser, 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) {
            System.err.println("SQLState: " + warn.getSQLState());
            System.err.println("Message:  " + warn.getMessage());
            System.err.println("Vendor: " + warn.getErrorCode());
            warn = warn.getNextWarning();
        }
    }

    return conn;

}

From source file:org.wso2.carbon.apimgt.migration.client.MigrationDBCreator.java

private void executeSQL(String sql) throws APIMigrationException {
    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;//from  ww w. ja v  a  2 s. c om
    }

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

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

        if (log.isDebugEnabled()) {
            log.debug(sql + " : " + updateCountTotal + " rows affected");
        }
        SQLWarning warning = connection.getWarnings();
        while (warning != null) {
            log.debug(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        connection.clearWarnings();
    } catch (SQLException e) {
        if ("X0Y32".equals(e.getSQLState()) || "42710".equals(e.getSQLState())) {
            // 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 APIMigrationException("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);
            }
        }
    }
}

From source file:org.hyperic.hq.plugin.sybase.SybaseSysmonCollector.java

public void collect() {
    Properties props = getProperties();
    log.debug("[collect] props=" + props);

    try {/*from w  w w .  j a  v  a  2s  .  c  o m*/
        setAvailability(Metric.AVAIL_DOWN);
        if (conn == null) {
            conn = createConnection(props);
        }
        stmt = conn.prepareCall("{call sp_sysmon '" + props.getProperty(INTERVAL) + "'}");
        stmt.executeUpdate();

        StringBuffer response = new StringBuffer();
        SQLWarning war = stmt.getWarnings();
        do {
            response.append(war.getMessage()).append("\n");
            war = war.getNextWarning();
        } while (war != null);
        trace.debug(response);

        String res = response.toString();

        Pattern pat = Pattern.compile("\n +Cache:(.*)\n");
        Matcher m = pat.matcher(res);
        while (m.find()) {
            final String cacheName = m.group(1).trim().replaceAll(" ", "_");
            if (trace.isDebugEnabled()) {
                trace.debug("->'" + cacheName + "'");
                trace.debug("->" + m.start());
            }
            String sec = res.substring(m.start());
            setValue(cacheName + ".Availability", Metric.AVAIL_UP);
            setValue(cacheName + ".CacheHitsRatio", get(sec, "Cache Hits", 5) / 100);
            setValue(cacheName + ".CacheMissesRatio", get(sec, "Cache Misses", 5) / 100);
        }

        // output per engine:
        // Engine 0                        0.0 %      0.0 %    100.0 %
        //
        // regex should only find lines starting with "Engine X                        X.X %"
        // engineid and percentage are in regex groups 1 and 2
        pat = Pattern.compile("\n +Engine (\\d)+\\s+(\\d+\\.\\d+) %.*");
        m = pat.matcher(res);
        while (m.find()) {
            try {
                final String engineId = m.group(1);
                final String cpuBusyVal = m.group(2);
                if (engineId != null && cpuBusyVal != null) {
                    setValue("EngineUtilization" + engineId.trim(),
                            Double.parseDouble(cpuBusyVal.trim()) / 100);
                }
                if (trace.isDebugEnabled()) {
                    trace.debug("Found Engine Utilization for engineid=" + engineId.trim() + " with value "
                            + Double.parseDouble(cpuBusyVal.trim()) / 100);
                }
            } catch (NumberFormatException e) {
                if (trace.isDebugEnabled()) {
                    trace.debug("Unable to parse number from: " + e.toString());
                }
            } catch (IndexOutOfBoundsException e) {
                if (trace.isDebugEnabled()) {
                    trace.debug("Unable to find group from matcher: " + e.toString());
                }
            }
        }

        setValue("Deadlocks", get(res, "Deadlock Percentage", 5));
        setValue("TotalLockReqs", get(res, "Total Lock Requests", 5));
        setValue("AvgLockContention", get(res, "Avg Lock Contention", 5));
        setValue("TotalCacheHitsRatio", get(res, "Total Cache Hits", 6) / 100);
        setValue("TotalCacheMissesRatio", get(res, "Total Cache Misses", 6) / 100);
        setValue("TDSPacketsReceived", get(res, "Total TDS Packets Rec'd", 6) / 100);
        setValue("TDSPacketsSent", get(res, "Total Bytes Rec'd", 5) / 100);
        setAvailability(Metric.AVAIL_UP);

    } catch (SQLException e) {
        setValue("Availability", Metric.AVAIL_DOWN);
        log.debug("[collect] Error " + e.getMessage());
        log.debug("[collect] Error " + getResult().toString());
        if (conn != null) {
            DBUtil.closeJDBCObjects(log, conn, null, null);
            conn = null;
        }
    } finally {
        if (conn != null) {
            DBUtil.closeJDBCObjects(log, null, stmt, null);
        }
    }

}

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

/**
 * executes given sql// www  . j a  v a  2 s .c  om
 *
 * @param sql
 * @throws Exception
 */
private void executeSQL(String sql) throws SQLException {

    // 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();
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.error("Error occurred while closing result set.", e);
            }
        }
    }
}

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

/**
 * executes given sql/*  w  w w. ja v  a 2 s.  c o  m*/
 *
 * @param sql
 * @throws Exception
 */
private void executeSQL(String sql) throws SQLException {

    // 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) {
            if (log.isDebugEnabled()) {
                log.debug(warning + " sql warning");//TODO:Check for if
            }
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.error("Error occurred while closing result set.", e);
            }
        }
    }
}

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

/**
 * executes given sql//from www.j  a v  a 2  s. co m
 *
 * @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);
            }
        }
    }
}