Example usage for java.sql Statement addBatch

List of usage examples for java.sql Statement addBatch

Introduction

In this page you can find the example usage for java.sql Statement addBatch.

Prototype

void addBatch(String sql) throws SQLException;

Source Link

Document

Adds the given SQL command to the current list of commands for this Statement object.

Usage

From source file:net.firejack.platform.core.config.upgrader.SchemaUpgrader.java

/**
 * This method update database package version and increase version number
 *
 * @param packageLookup - Openflame Package lookup
 * @param version       - database version
 * @return version//from  ww  w.  j  ava  2 s  .  co m
 */
private Version updateDatabaseVersion(String packageLookup, Version version) {
    try {
        Connection connection = dataSource.getConnection();
        try {
            connection.setAutoCommit(true);

            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            statement.addBatch("UPDATE opf_registry_node SET database_version = " + version.getToVersion() + " "
                    + "WHERE lookup = '" + packageLookup + "';");
            try {
                statement.executeBatch();
                return new Version(version.getToVersion());
            } finally {
                JdbcUtils.closeStatement(statement);
            }
        } finally {
            connection.setAutoCommit(false);
            JdbcUtils.closeConnection(connection);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.zionex.t3sinc.util.db.SincDatabaseUtility.java

public int[] executeBatch(Statement statement, List sqlStrings) throws SQLException {
    for (Iterator iterator = sqlStrings.iterator(); iterator.hasNext();) {
        statement.addBatch(iterator.next().toString());
    }/*from  www.  j  av  a 2 s .c  o  m*/
    return statement.executeBatch();
}

From source file:it.attocchi.db.JdbcConnector.java

/**
 * //from  ww w . j  a v a2s  .c  o  m
 * @param aQuery
 * @param params
 * @return
 * @throws SQLException
 */
public int executeBatchUpdate(boolean keepConnOpen, List<String> batchQuery) throws Exception {
    int res = 0;

    try {

        if (ListUtils.isNotEmpty(batchQuery)) {

            logger.debug(batchQuery.size());

            Connection connection = getConnection();

            // connection.setAutoCommit(false);

            Statement statement = connection.createStatement();
            for (String aQuery : batchQuery) {
                statement.addBatch(aQuery);
            }

            int[] counts = statement.executeBatch();

            for (int count : counts) {
                res = res + count;
            }
            // connection.commit();
        }

    } finally {
        if (!keepConnOpen)
            close();
    }

    return res;
}

From source file:org.kuali.rice.krad.dao.jdbc.PostDataLoadEncryptionDaoJdbc.java

public boolean performEncryption(final String tableName,
        final List<Map<String, List<String>>> rowsToEncryptColumnNameOldNewValuesMap) throws Exception {

    Boolean success = (Boolean) getJdbcTemplate().execute(new ConnectionCallback() {
        public Object doInConnection(Connection conn) throws SQLException, DataAccessException {
            try {
                conn.setAutoCommit(false);
                Statement statement = conn.createStatement();
                int counter = 0;
                for (Map<String, List<String>> columnNameOldNewValuesMap : rowsToEncryptColumnNameOldNewValuesMap) {
                    statement.addBatch(getUpdateBackupTableColumnsSql(tableName, columnNameOldNewValuesMap));
                    counter++;/*from ww  w . j a v  a 2s . c  o  m*/
                }
                statement.executeBatch();
                conn.commit();
                LOG.info(new StringBuffer("Encrypted ").append(" attributes of table ").append(tableName));
            } catch (Exception e) {
                LOG.error(new StringBuffer("Caught exception, while encrypting ")
                        .append(" attributes of table ").append(tableName), e);
                conn.rollback();
                return false;
            }
            return true;
        }
    });
    return success;
}

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

/**
 * Execute the given SQL script./*from w ww . 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.gdo.project.util.SqlUtils.java

@Deprecated
public static void batchUpdate(StclContext stclContext, String[] queries) throws SQLException {
    Connection con = null;/*  w w  w . jav a2 s.  c  o m*/
    Statement stmt = null;
    try {
        con = getConnection(stclContext);
        stmt = con.createStatement();
        for (String query : queries) {
            if (!StringUtils.isEmpty(query))
                stmt.addBatch(query);
        }
        stmt.executeBatch();
    } finally {
        if (stmt != null)
            closeStatement(stclContext, stmt);
    }
}

From source file:org.kuali.rice.kew.test.TestUtilities.java

public static void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource,
        final String edenSchemaName, final List<String> dontClear) {
    LOG.info("Clearing tables for schema " + edenSchemaName);
    if (dataSource == null) {
        Assert.fail("Null data source given");
    }/*  ww  w.j av a 2 s.co  m*/
    if (edenSchemaName == null || edenSchemaName.equals("")) {
        Assert.fail("Empty eden schema name given");
    }
    new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            JdbcTemplate template = new JdbcTemplate(dataSource);
            return template.execute(new StatementCallback() {
                public Object doInStatement(Statement statement) throws SQLException {
                    List<String> reEnableConstraints = new ArrayList<String>();
                    ResultSet resultSet = statement.getConnection().getMetaData().getTables(null,
                            edenSchemaName, null, new String[] { "TABLE" });
                    while (resultSet.next()) {
                        String tableName = resultSet.getString("TABLE_NAME");
                        if (tableName.startsWith("EN_") && !dontClear.contains(tableName)) {
                            ResultSet keyResultSet = statement.getConnection().getMetaData()
                                    .getExportedKeys(null, edenSchemaName, tableName);
                            while (keyResultSet.next()) {
                                String fkName = keyResultSet.getString("FK_NAME");
                                String fkTableName = keyResultSet.getString("FKTABLE_NAME");
                                statement.addBatch(
                                        "ALTER TABLE " + fkTableName + " DISABLE CONSTRAINT " + fkName);
                                reEnableConstraints
                                        .add("ALTER TABLE " + fkTableName + " ENABLE CONSTRAINT " + fkName);
                            }
                            keyResultSet.close();
                            statement.addBatch("DELETE FROM " + tableName);
                        }
                    }
                    for (String constraint : reEnableConstraints) {
                        statement.addBatch(constraint);
                    }
                    statement.executeBatch();
                    resultSet.close();
                    return null;
                }
            });
        }
    });
    LOG.info("Tables successfully cleared for schema " + edenSchemaName);
}

From source file:org.apache.lucene.store.jdbc.support.JdbcTemplate.java

/**
 * A template method to execute a set of sqls in batch.
 *///from w ww . j  a  va  2  s .  c  o m
public int[] executeBatch(String[] sqls) throws JdbcStoreException {
    Connection con = DataSourceUtils.getConnection(dataSource);
    Statement statement = null;
    try {
        statement = con.createStatement();
        //            statement.setQueryTimeout(settings.getQueryTimeout());
        for (String sql : sqls) {
            statement.addBatch(sql);
        }
        return statement.executeBatch();
    } catch (SQLException e) {
        if (log.isTraceEnabled()) {
            log.trace("Failed to execute sql [" + Arrays.toString(sqls) + "]", e);
        }
        throw new JdbcStoreException("Failed to execute [" + Arrays.toString(sqls) + "]", e);
    } finally {
        DataSourceUtils.closeStatement(statement);
        DataSourceUtils.releaseConnection(con);
    }
}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

private static void IntOutNoneRecordsStoreIntoDB(Map<String, AlarmNoMark> iniOutNoneRecords,
        ApplicationContext context) {//from  w  w w  .  j  a va2  s .  com
    Connection conn = null;
    String sql = "";
    try {
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientLybc");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = iniOutNoneRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            AlarmNoMark pos = iniOutNoneRecords.get(key);
            sql = "insert into TAB_ALARM_NOMARK " + " (LICENCE,BEGIN_TIME,END_TIME,ROAD) " + " values (" + "'"
                    + pos.getLicense() + "'," + "'" + pos.getBeginTime() + "'," + "'" + pos.getEndTime() + "',"
                    + "'" + pos.getRoad() + "')";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB TAB_ALARM_NOMARK success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        iniOutNoneRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

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

public void batchUpdate() throws SQLException {

    Statement stmt = null;
    try {//  w  w w.  ja v  a 2s . co m

        this.con.setAutoCommit(false);
        stmt = this.con.createStatement();

        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)");

        int[] updateCounts = stmt.executeBatch();
        this.con.commit();

    } catch (BatchUpdateException b) {
        JDBCTutorialUtilities.printBatchUpdateException(b);
    } catch (SQLException ex) {
        JDBCTutorialUtilities.printSQLException(ex);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
        this.con.setAutoCommit(true);
    }
}