List of usage examples for java.sql SQLWarning getErrorCode
public int getErrorCode()
SQLException
object. From source file:edu.lternet.pasta.token.TokenManager.java
/** * Returns a connection to the database. * * @return The database Connection object. *//* ww w.j av a 2 s . co 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:cc.tooyoung.common.db.JdbcTemplate.java
/** * Throw an SQLWarningException if we're not ignoring warnings, * else log the warnings (at debug level). * @param stmt the current JDBC statement * @throws SQLWarningException if not ignoring warnings * @see org.springframework.jdbc.SQLWarningException */// www .j a v a 2s . co m protected void handleWarnings(Statement stmt) throws SQLException { if (isIgnoreWarnings()) { if (ApiLogger.isTraceEnabled()) { SQLWarning warningToLog = stmt.getWarnings(); while (warningToLog != null) { ApiLogger.trace("SQLWarning ignored: SQL state '" + warningToLog.getSQLState() + "', error code '" + warningToLog.getErrorCode() + "', message [" + warningToLog.getMessage() + "]"); warningToLog = warningToLog.getNextWarning(); } } } else { handleWarnings(stmt.getWarnings()); } }
From source file:lib.JdbcTemplate.java
/** * Throw an SQLWarningException if we're not ignoring warnings, * else log the warnings (at debug level). * @param stmt the current JDBC statement * @throws SQLWarningException if not ignoring warnings * @see org.springframework.jdbc.SQLWarningException *///w w w . j a v a 2s. c o m protected void handleWarnings(Statement stmt) throws SQLException { if (isIgnoreWarnings()) { if (logger.isDebugEnabled()) { 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(); } } } else { handleWarnings(stmt.getWarnings()); } }
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(); }//from ww w.ja v a 2s . c o m } warningElem.addAttribute("message", message); warningsElem.addSubElement(warningElem); warnings = warnings.getNextWarning(); } return warningsElem; } return null; }
From source file:org.gbif.ipt.service.manage.impl.SourceManagerImpl.java
private Connection getDbConnection(SqlSource source) throws SQLException { Connection conn = null;// w w w .j a v a2s . 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:org.sakaiproject.util.conversion.SchemaConversionController.java
public boolean migrate(DataSource datasource, SchemaConversionHandler convert, SchemaConversionDriver driver) throws SchemaConversionException { // issues://from www. j a v a 2 s. c om // 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.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 av a 2 s. c om * * @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.springframework.jdbc.datasource.init.ScriptUtils.java
/** * Execute the given SQL script.//from w w w. ja v a2s.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 — 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); } }