Example usage for java.sql SQLException getNextException

List of usage examples for java.sql SQLException getNextException

Introduction

In this page you can find the example usage for java.sql SQLException getNextException.

Prototype

public SQLException getNextException() 

Source Link

Document

Retrieves the exception chained to this SQLException object by setNextException(SQLException ex).

Usage

From source file:netflow.DatabaseProxy.java

public void saveHosts(Map<String, HostTraffic> cache, java.util.Date date) {
    if (cache.size() == 0) {
        log.debug("Host cache empty");
        return;/*from  w w  w .j a v a2s.  c  o  m*/
    }
    log.debug("Saving " + cache.size() + " records for " + date);
    String sql = getQuery("neflow.details.insert");
    try {
        PreparedStatement pstmt = con.prepareStatement(sql);
        Timestamp t = new java.sql.Timestamp(date.getTime());
        for (String key : cache.keySet()) {
            HostTraffic traffic = cache.get(key);
            if (!hasRecord(t, traffic.getHostAddress(), traffic.getNetworkId())) {
                pstmt.setTimestamp(1, t);
                pstmt.setString(2, traffic.getHostAddress());
                pstmt.setInt(3, traffic.getNetworkId());
                pstmt.setLong(4, traffic.getInputBytes());
                pstmt.setLong(5, traffic.getOutputBytes());
                pstmt.addBatch();
            }
        }
        int[] results = pstmt.executeBatch();
        log.info("saveHosts(): saved " + results.length + " records");
        pstmt.close();
        pstmt.clearParameters();
    } catch (SQLException e) {
        log.error("Saving hosts error: " + e.getMessage());
        SQLException ex = e.getNextException();
        if (ex != null) {
            log.error(ex.getMessage());
        }
        e.printStackTrace(System.err);
    }
}

From source file:at.rocworks.oa4j.logger.dbs.NoSQLJDBC.java

public int storeData(DataList list) {
    try {/*from   ww  w .jav a  2  s . c o m*/
        Connection conn = dataSourceWrite.getConnection();
        if (conn != null) {
            int i;
            DataItem item;
            EventItem event;
            Object tag;

            conn.setAutoCommit(false);
            PreparedStatement stmt;

            Date t1 = new Date();

            stmt = conn.prepareStatement(sqlInsertStmt);
            for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                if (!(item instanceof EventItem))
                    continue;
                event = (EventItem) item;
                ValueItem val = event.getValue();

                tag = this.getTagOfDp(event.getDp());
                if (tag == null)
                    continue;

                if (tag instanceof Long)
                    stmt.setLong(1, (Long) tag);
                else if (tag instanceof String)
                    stmt.setString(1, (String) tag);

                java.sql.Timestamp ts = new java.sql.Timestamp(event.getTimeMS());
                ts.setNanos(event.getNanos());

                stmt.setTimestamp(2, ts, cal);

                Double dval = val.getDouble();
                if (dval != null) {
                    stmt.setDouble(3, dval);
                } else {
                    stmt.setNull(3, Types.DOUBLE);
                }

                // value_string                    
                stmt.setString(4, val.getString());

                // value_timestamp
                if (val.getTimeMS() != null)
                    stmt.setTimestamp(5, new java.sql.Timestamp(val.getTimeMS()), cal);
                else
                    stmt.setNull(5, Types.TIMESTAMP);

                // status, manager, user
                if (event.hasAttributes()) {
                    stmt.setLong(6, event.getStatus());
                    stmt.setInt(7, event.getManager());
                    stmt.setInt(8, event.getUser());
                } else {
                    stmt.setNull(6, Types.INTEGER);
                    stmt.setNull(7, Types.INTEGER);
                    stmt.setNull(8, Types.INTEGER);
                }

                //JDebug.out.log(Level.FINE, "{0}:{1}/{2} [{3}]", new Object[] {i, element_id.toString(), ts.toString(), item.toString()});

                stmt.addBatch();
            }
            try {
                stmt.executeBatch(); // TODO check result? int[] res =
            } catch (BatchUpdateException ex) {
                JDebug.out.log(Level.SEVERE, "Batch exception {0} update count {1}.",
                        new Object[] { ex.getErrorCode(), ex.getUpdateCounts().length });
                JDebug.StackTrace(Level.SEVERE, ex);
            } catch (SQLException ex) {
                SQLException current = ex;
                do {
                    JDebug.out.log(Level.SEVERE, "SQL exception {0}.", new Object[] { ex.getErrorCode() });
                    JDebug.StackTrace(Level.SEVERE, current);
                } while ((current = current.getNextException()) != null);
                //                    for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                //                        JDebug.out.log(Level.INFO, "{0}", item.toJSONObject());
                //                    }
            }
            Date t2 = new Date();
            stmt.close();

            afterInsert(conn);

            conn.commit();
            conn.close();
            addServerStats(list.getHighWaterMark(), t2.getTime() - t1.getTime());
            return INoSQLInterface.OK;
        } else {
            JDebug.StackTrace(Level.SEVERE, "no connection!");
            return INoSQLInterface.ERR_REPEATABLE;
        }
    } catch (Exception ex) {
        JDebug.StackTrace(Level.SEVERE, ex);
        return INoSQLInterface.ERR_REPEATABLE;
    }
}

From source file:org.qi4j.entitystore.sql.SQLEntityStoreMixin.java

public StateCommitter applyChanges(final EntityStoreUnitOfWork unitofwork, final Iterable<EntityState> states) {
    return new StateCommitter() {

        public void commit() {
            Connection connection = null;
            PreparedStatement insertPS = null;
            PreparedStatement updatePS = null;
            PreparedStatement removePS = null;
            try {
                connection = database.getConnection();
                insertPS = database.prepareInsertEntityStatement(connection);
                updatePS = database.prepareUpdateEntityStatement(connection);
                removePS = database.prepareRemoveEntityStatement(connection);
                for (EntityState state : states) {
                    EntityStatus status = state.status();
                    DefaultEntityState defState = ((SQLEntityState) state).getDefaultEntityState();
                    Long entityPK = ((SQLEntityState) state).getEntityPK();
                    if (EntityStatus.REMOVED.equals(status)) {
                        database.populateRemoveEntityStatement(removePS, entityPK, state.identity());
                        removePS.addBatch();
                    } else {
                        StringWriter writer = new StringWriter();
                        writeEntityState(defState, writer, unitofwork.identity());
                        writer.flush();/*from   w  w  w.jav  a2 s.com*/
                        if (EntityStatus.UPDATED.equals(status)) {
                            Long entityOptimisticLock = ((SQLEntityState) state).getEntityOptimisticLock();
                            database.populateUpdateEntityStatement(updatePS, entityPK, entityOptimisticLock,
                                    defState.identity(), writer.toString(), unitofwork.currentTime());
                            updatePS.addBatch();
                        } else if (EntityStatus.NEW.equals(status)) {
                            database.populateInsertEntityStatement(insertPS, entityPK, defState.identity(),
                                    writer.toString(), unitofwork.currentTime());
                            insertPS.addBatch();
                        }
                    }
                }

                removePS.executeBatch();
                insertPS.executeBatch();
                updatePS.executeBatch();

                connection.commit();

            } catch (SQLException sqle) {
                SQLUtil.rollbackQuietly(connection);
                if (LOGGER.isDebugEnabled()) {
                    StringWriter sb = new StringWriter();
                    sb.append(
                            "SQLException during commit, logging nested exceptions before throwing EntityStoreException:\n");
                    SQLException e = sqle;
                    while (e != null) {
                        e.printStackTrace(new PrintWriter(sb, true));
                        e = e.getNextException();
                    }
                    LOGGER.debug(sb.toString());
                }
                throw new EntityStoreException(sqle);
            } catch (RuntimeException re) {
                SQLUtil.rollbackQuietly(connection);
                throw new EntityStoreException(re);
            } finally {
                SQLUtil.closeQuietly(insertPS);
                SQLUtil.closeQuietly(updatePS);
                SQLUtil.closeQuietly(removePS);
                SQLUtil.closeQuietly(connection);
            }
        }

        public void cancel() {
        }

    };
}

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();/*from w ww  .  j av  a 2 s .  co  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);
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectUpdater.java

private void handleConstraintViolationException(Session session, ConstraintViolationException ex,
        OperationResult result) {//from ww  w  .  j a  v a 2 s  .c  o  m

    // BRUTAL HACK - in PostgreSQL, concurrent changes in parentRefOrg sometimes cause the following exception
    // "duplicate key value violates unique constraint "XXXX". This is *not* an ObjectAlreadyExistsException,
    // more likely it is a serialization-related one.
    //
    // TODO: somewhat generalize this approach - perhaps by retrying all operations not dealing with OID/name uniqueness

    SQLException sqlException = transactionHelper.findSqlException(ex);
    if (sqlException != null) {
        SQLException nextException = sqlException.getNextException();
        LOGGER.debug("ConstraintViolationException = {}; SQL exception = {}; embedded SQL exception = {}",
                new Object[] { ex, sqlException, nextException });
        String[] ok = new String[] { "duplicate key value violates unique constraint \"m_org_closure_pkey\"",
                "duplicate key value violates unique constraint \"m_reference_pkey\"" };
        String msg1;
        if (sqlException.getMessage() != null) {
            msg1 = sqlException.getMessage();
        } else {
            msg1 = "";
        }
        String msg2;
        if (nextException != null && nextException.getMessage() != null) {
            msg2 = nextException.getMessage();
        } else {
            msg2 = "";
        }
        for (int i = 0; i < ok.length; i++) {
            if (msg1.contains(ok[i]) || msg2.contains(ok[i])) {
                transactionHelper.rollbackTransaction(session, ex, result, false);
                throw new SerializationRelatedException(ex);
            }
        }
    }
}

From source file:org.projectforge.web.wicket.WicketApplication.java

@Override
protected void init() {
    super.init();
    // Own error page for deployment mode and UserException and AccessException.
    getRequestCycleListeners().add(new AbstractRequestCycleListener() {
        /**/* w  ww  . j  a v  a  2s . c o m*/
         * Log only non ProjectForge exceptions.
         * @see org.apache.wicket.request.cycle.AbstractRequestCycleListener#onException(org.apache.wicket.request.cycle.RequestCycle,
         *      java.lang.Exception)
         */
        @Override
        public IRequestHandler onException(final RequestCycle cycle, final Exception ex) {
            // in case of expired session, please redirect to home page
            if (ex instanceof PageExpiredException) {
                return new RenderPageRequestHandler(new PageProvider(getHomePage()));
            }
            final Throwable rootCause = ExceptionHelper.getRootCause(ex);
            // log.error(rootCause.getMessage(), ex);
            // if (rootCause instanceof ProjectForgeException == false) {
            // return super.onException(cycle, ex);
            // }
            // return null;
            if (isDevelopmentSystem() == true) {
                log.error(ex.getMessage(), ex);
                if (rootCause instanceof SQLException) {
                    SQLException next = (SQLException) rootCause;
                    while ((next = next.getNextException()) != null) {
                        log.error(next.getMessage(), next);
                    }
                }
                return super.onException(cycle, ex);
            } else {
                // Show always this error page in production mode:
                return new RenderPageRequestHandler(new PageProvider(new ErrorPage(ex)));
            }
        }
    });

    getApplicationSettings().setDefaultMaximumUploadSize(Bytes.megabytes(100));
    getMarkupSettings().setDefaultMarkupEncoding("utf-8");
    final MyAuthorizationStrategy authStrategy = new MyAuthorizationStrategy();
    getSecuritySettings().setAuthorizationStrategy(authStrategy);
    getSecuritySettings().setUnauthorizedComponentInstantiationListener(authStrategy);
    // Prepend the resource bundle for overwriting some Wicket default localizations (such as StringValidator.*)
    getResourceSettings().getStringResourceLoaders().add(new BundleStringResourceLoader(RESOURCE_BUNDLE_NAME));
    getResourceSettings().setThrowExceptionOnMissingResource(false); // Don't throw MissingResourceException for missing i18n keys.
    getApplicationSettings().setPageExpiredErrorPage(PageExpiredPage.class); // Don't show expired page.
    // getSessionSettings().setMaxPageMaps(20); // Map up to 20 pages per session (default is 5).
    getComponentInstantiationListeners().add(new SpringComponentInjector(this));
    getApplicationSettings().setInternalErrorPage(ErrorPage.class);
    // getRequestCycleSettings().setGatherExtendedBrowserInfo(true); // For getting browser width and height.

    // Select2:
    // final ApplicationSettings select2Settings = ApplicationSettings.get();
    // select2Settings.setIncludeJavascript(false);

    final XmlWebApplicationContext webApplicationContext = (XmlWebApplicationContext) WebApplicationContextUtils
            .getWebApplicationContext(getServletContext());
    final ConfigurableListableBeanFactory beanFactory = webApplicationContext.getBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    final LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean) beanFactory
            .getBean("&sessionFactory");

    // if ("true".equals(System.getProperty(SYSTEM_PROPERTY_HSQLDB_18_UPDATE)) == true) {
    // try {
    // log.info("Send SHUTDOWN COMPACT to upgrade data-base version:");
    // final DataSource dataSource = (DataSource)beanFactory.getBean("dataSource");
    // dataSource.getConnection().createStatement().execute("SHUTDOWN COMPACT");
    // log.fatal("************ PLEASE RESTART APPLICATION NOW FOR PROPER INSTALLATION !!!!!!!!!!!!!! ************");
    // return;
    // } catch (final SQLException ex) {
    // log.fatal("Data-base SHUTDOWN COMPACT failed: " + ex.getMessage());
    // }
    // }
    final org.hibernate.cfg.Configuration hibernateConfiguration = localSessionFactoryBean.getConfiguration();
    HibernateUtils.setConfiguration(hibernateConfiguration);
    final ServletContext servletContext = getServletContext();
    final String configContextPath = configXml.getServletContextPath();
    String contextPath;
    if (StringUtils.isBlank(configContextPath) == true) {
        contextPath = servletContext.getContextPath();
        configXml.setServletContextPath(contextPath);
    } else {
        contextPath = configContextPath;
    }
    log.info("Using servlet context path: " + contextPath);
    if (configuration.getBeanFactory() == null) {
        configuration.setBeanFactory(beanFactory);
    }
    configuration.setConfigurationDao(configurationDao);
    SystemInfoCache.internalInitialize(systemInfoCache);
    WicketUtils.setContextPath(contextPath);
    UserFilter.initialize(userDao, contextPath);
    if (this.wicketApplicationFilter != null) {
        this.wicketApplicationFilter.setApplication(this);
    } else {
        throw new RuntimeException("this.wicketApplicationFilter is null");
    }
    daoRegistry.init();

    final PluginsRegistry pluginsRegistry = PluginsRegistry.instance();
    pluginsRegistry.set(beanFactory, getResourceSettings());
    pluginsRegistry.set(systemUpdater);
    pluginsRegistry.initialize();

    for (final Map.Entry<String, Class<? extends WebPage>> mountPage : WebRegistry.instance().getMountPages()
            .entrySet()) {
        final String path = mountPage.getKey();
        final Class<? extends WebPage> pageClass = mountPage.getValue();
        mountPage(path, pageClass);
        mountedPages.put(pageClass, path);
    }
    if (isDevelopmentSystem() == true) {
        if (isStripWicketTags() == true) {
            log.info("Strip Wicket tags also in development mode at default (see context.xml).");
            Application.get().getMarkupSettings().setStripWicketTags(true);
        }
        getDebugSettings().setOutputMarkupContainerClassName(true);
    }
    log.info("Default TimeZone is: " + TimeZone.getDefault());
    if ("UTC".equals(TimeZone.getDefault().getID()) == false) {
        for (final String str : UTC_RECOMMENDED) {
            log.fatal(str);
        }
        for (final String str : UTC_RECOMMENDED) {
            System.err.println(str);
        }
    }
    log.info("user.timezone is: " + System.getProperty("user.timezone"));
    cronSetup.initialize();
    log.info(AppVersion.APP_ID + " " + AppVersion.NUMBER + " (" + AppVersion.RELEASE_TIMESTAMP
            + ") initialized.");

    PFUserContext.setUser(DatabaseUpdateDao.__internalGetSystemAdminPseudoUser()); // Logon admin user.
    if (systemUpdater.isUpdated() == false) {
        // Force redirection to update page:
        UserFilter.setUpdateRequiredFirst(true);
    }
    PFUserContext.setUser(null);
    UserXmlPreferencesCache.setInternalInstance(userXmlPreferencesCache);
    LoginHandler loginHandler;
    if (StringUtils.isNotBlank(configXml.getLoginHandlerClass()) == true) {
        loginHandler = (LoginHandler) BeanHelper.newInstance(configXml.getLoginHandlerClass());
    } else {
        loginHandler = new LoginDefaultHandler();
    }
    if (loginHandler == null) {
        log.error("Can't load login handler '" + configXml.getLoginHandlerClass()
                + "'. No login will be possible!");
    } else {
        loginHandler.initialize();
        Login.getInstance().setLoginHandler(loginHandler);
    }
    try {
        StorageClient.getInstance(); // Initialize storage
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
    }
    getPageSettings().setRecreateMountedPagesAfterExpiry(false);

    // initialize ical4j to be more "relaxed"
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);

    // initialize styles compiler
    try {
        final LessWicketApplicationInstantiator lessInstantiator = new LessWicketApplicationInstantiator(this,
                "styles", "projectforge.less", "projectforge.css");
        lessInstantiator.instantiate();
    } catch (final Exception e) {
        log.error("Unable to instantiate wicket less compiler", e);
    }
}

From source file:org.n52.sos.encode.OwsEncoderv110.java

private void addExceptionMessages(StringBuilder exceptionText, Throwable exception) {
    exceptionText.append("[EXCEPTION]: \n");
    final String localizedMessage = exception.getLocalizedMessage();
    final String message = exception.getMessage();
    if (localizedMessage != null && message != null) {
        if (!message.equals(localizedMessage)) {
            JavaHelper.appendTextToStringBuilderWithLineBreak(exceptionText, message);
        }//from   www.  j  ava  2  s .  co  m
        JavaHelper.appendTextToStringBuilderWithLineBreak(exceptionText, localizedMessage);
    } else {
        JavaHelper.appendTextToStringBuilderWithLineBreak(exceptionText, localizedMessage);
        JavaHelper.appendTextToStringBuilderWithLineBreak(exceptionText, message);
    }

    //recurse cause if necessary
    if (exception.getCause() != null) {
        exceptionText.append("[CAUSED BY]\n");
        addExceptionMessages(exceptionText, exception.getCause());
    }

    //recurse SQLException if necessary
    if (exception instanceof SQLException) {
        SQLException sqlException = (SQLException) exception;
        if (sqlException.getNextException() != null) {
            exceptionText.append("[NEXT SQL EXCEPTION]\n");
            addExceptionMessages(exceptionText, sqlException.getNextException());
        }
    }
}

From source file:org.jtotus.database.LocalJDBC.java

public double[] fetchPeriod(String tableName, DateTime startDate, DateTime endDate, String type) {
    BigDecimal retValue = null;//from w ww.jav  a2s  .com
    PreparedStatement pstm = null;
    java.sql.Date retDate = null;
    ResultSet results = null;
    ArrayList<Double> closingPrices = new ArrayList<Double>(600);
    Connection connection = null;

    try {
        String query = "SELECT " + type + ", DATE FROM " + this.normTableName(tableName)
                + " WHERE DATE>=? AND DATE<=? ORDER BY DATE ASC";
        // this.createTable(connection, this.normTableName(tableName));

        connection = this.getConnection();
        pstm = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        java.sql.Date startSqlDate = new java.sql.Date(startDate.getMillis());
        pstm.setDate(1, startSqlDate);

        java.sql.Date endSqlDate = new java.sql.Date(endDate.getMillis());
        pstm.setDate(2, endSqlDate);

        DateIterator dateIter = new DateIterator(startDate, endDate);

        results = pstm.executeQuery();
        DateTime dateCheck;

        if (debug) {
            System.out.printf("start data %s end date: %s\n", startSqlDate.toString(), endSqlDate.toString());
        }

        while (dateIter.hasNext()) {
            dateCheck = dateIter.nextInCalendar();

            if (results.next()) {
                retValue = results.getBigDecimal(1);
                retDate = results.getDate(2);

                DateTime compCal = new DateTime(retDate.getTime());
                if (compCal.getDayOfMonth() == dateCheck.getDayOfMonth()
                        && compCal.getMonthOfYear() == dateCheck.getMonthOfYear()
                        && compCal.getYear() == dateCheck.getYear()) {
                    closingPrices.add(retValue.doubleValue());
                    continue;
                } else {
                    results.previous();
                }
            }

            BigDecimal failOverValue = getFetcher().fetchData(tableName, dateCheck, type);
            if (failOverValue != null) {
                closingPrices.add(failOverValue.doubleValue());
            }
        }

    } catch (SQLException ex) {
        System.err.printf("LocalJDBC Unable to find date for:'%s' from'%s' Time" + startDate.toDate() + "\n",
                "Cosing Price", tableName);
        ex.printStackTrace();
        SQLException xp = null;
        while ((xp = ex.getNextException()) != null) {
            xp.printStackTrace();
        }

    } finally {
        try {
            if (results != null)
                results.close();
            if (pstm != null)
                pstm.close();
            if (connection != null)
                connection.close();
            //                System.out.printf("Max connect:%d in use:%d\n",mainPool.getMaxConnections(), mainPool.getActiveConnections());
            //                mainPool.dispose();

        } catch (SQLException ex) {
            Logger.getLogger(LocalJDBC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return ArrayUtils.toPrimitive(closingPrices.toArray(new Double[0]));
}

From source file:com.excilys.ebi.bank.jdbc.SimpleBatchResourceDatabasePopulator.java

/**
 * Execute the given SQL script.//from ww w. j  av a2s  .  com
 * <p>
 * The script will normally be loaded by classpath. There should be one
 * statement per line. Any {@link #setSeparator(String) statement
 * separators} will be removed.
 * <p>
 * <b>Do not use this method to execute DDL if you expect rollback.</b>
 *
 * @param connection
 *            the JDBC Connection with which to perform JDBC operations
 * @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 of not to continue in the event of specifically an
 *            error on a <code>DROP</code>
 */
private void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError,
        boolean ignoreFailedDrops) throws SQLException, IOException {

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Executing SQL script from " + resource);
    }

    long startTime = System.currentTimeMillis();
    Iterator<String> statements = IOUtils.lineIterator(resource.getReader());
    int lineNumber = 0;

    boolean initialAutoCommitState = connection.getAutoCommit();

    connection.setAutoCommit(false);
    Statement stmt = connection.createStatement();
    try {
        while (statements.hasNext()) {
            String statement = statements.next();
            lineNumber++;
            try {
                stmt.addBatch(statement);

                if (lineNumber % batchSize == 0) {
                    stmt.executeBatch();
                    connection.commit();
                }
            } catch (SQLException ex) {
                boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
                if (continueOnError || (dropStatement && ignoreFailedDrops)) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Failed to execute SQL script statement at line " + lineNumber
                                + " of resource " + resource + ": " + statement, ex);
                    }
                } else {
                    Exception nextException = ex.getNextException();
                    throw new ScriptStatementFailedException(statement, lineNumber, resource,
                            nextException != null ? nextException : ex);
                }
            }
        }
    } finally {
        stmt.executeBatch();
        connection.commit();

        connection.setAutoCommit(initialAutoCommitState);

        try {
            stmt.close();
        } catch (Throwable ex) {
            LOGGER.debug("Could not close JDBC Statement", ex);
        }
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Done executing SQL script from " + resource + " in " + elapsedTime + " ms.");
    }
}

From source file:com.hangum.tadpole.importdb.core.dialog.importdb.sql.SQLToDBImportDialog.java

/**
 * select? execute  .//from w ww.ja  v a  2s .  c  o  m
 * 
 * @param listQuery
 * @throws Exception
 */
private int runSQLExecuteBatch(List<String> listQuery) throws Exception {
    java.sql.Connection conn = null;
    Statement statement = null;
    int result = 0;

    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        conn = client.getDataSource().getConnection();
        conn.setAutoCommit(false);
        statement = conn.createStatement();
        int count = 0;

        for (String strQuery : listQuery) {
            if ("".equals(StringUtils.trimToEmpty(strQuery))) //$NON-NLS-1$
                continue;

            statement.addBatch(strQuery);
            if (++count % batchSize == 0) {
                try {
                    statement.executeBatch();
                } catch (SQLException e) {
                    logger.error("Execute Batch error", e); //$NON-NLS-1$
                    bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$

                    SQLException ne = e.getNextException();
                    while (ne != null) {
                        logger.error("NEXT SQLException is ", ne);//$NON-NLS-1$
                        bufferBatchResult.append(ne.getMessage() + "\n");
                        ne = ne.getNextException();
                    }

                    if (btnIgnore.getSelection()) {
                        conn.commit();
                        continue;
                    } else {
                        conn.rollback();
                        result = -1;
                        break;
                    }
                }
            }
        }

        statement.executeBatch();
        conn.commit();
        conn.setAutoCommit(true);

        if (result < 0 && !"".equals(bufferBatchResult.toString())) { //$NON-NLS-1$
            MessageDialog.openError(null, Messages.CsvToRDBImportDialog_4, bufferBatchResult.toString());
        }
    } catch (SQLException e) {
        logger.error("Execute Batch error", e); //$NON-NLS-1$
        bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$
        if (btnIgnore.getSelection()) {
            conn.commit();
        } else {
            conn.rollback();
        }

        SQLException ne = e.getNextException();
        while (ne != null) {
            logger.error("Execute Batch error", e); //$NON-NLS-1$
            bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$
            ne = ne.getNextException();
        }
    } catch (Exception e) {
        result = -1;
        logger.error("Execute Batch error", e); //$NON-NLS-1$
        bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$
        conn.rollback();
        throw e;
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (Exception e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return result;
}