Example usage for java.sql Statement executeBatch

List of usage examples for java.sql Statement executeBatch

Introduction

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

Prototype

int[] executeBatch() throws SQLException;

Source Link

Document

Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

Usage

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 av  a2 s  .c o  m
    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:org.apache.lucene.store.jdbc.support.JdbcTemplate.java

/**
 * A template method to execute a set of sqls in batch.
 *//*from   w w  w . j  a va  2s  .  c om*/
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.excilys.ebi.bank.jdbc.SimpleBatchResourceDatabasePopulator.java

/**
 * Execute the given SQL script.//from   w ww.  j ava  2  s  .  co m
 * <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.china317.gmmp.gmmp_report_analysis.App.java

private static void PtmOverSpeedRecordsStoreIntoDB(Map<String, PtmOverSpeed> overSpeedRecords,
        ApplicationContext context) {/*from w w w  .java 2 s  . c  o m*/
    // INSERT INTO
    // TAB_ALARM_OVERSPEED(LICENCE,BEGIN_TIME,END_TIME,SPEED,IS_END,AREA)
    // SELECT LICENSE,BEGINTIME,ENDTIME,AVGSPEED,'1',FLAG FROM
    // ALARMOVERSPEED_REA WHERE BUSINESSTYPE = '2'
    String sql = "";
    Connection conn = null;
    try {
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientPtm");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = overSpeedRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            PtmOverSpeed pos = overSpeedRecords.get(key);
            sql = "insert into TAB_ALARM_OVERSPEED " + " (LICENCE,BEGIN_TIME,END_TIME,SPEED,IS_END,AREA) "
                    + " values ('" + pos.getLicense() + "','" + pos.getBeginTime() + "','" + pos.getEndTIme()
                    + "'," + pos.getAvgSpeed() + "," + "1" + "," + pos.getFlag() + ")";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB OverSpeed success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        overSpeedRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

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++;/*w  w  w .  ja va2 s .co 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: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   w  w  w. j  a  v a 2 s .c  om*/
 */
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:dao.RuleDao.java

/**
 * Deletes a rule from a target DB and from the local APEX db
 * /*from   www  .  j av a2  s.c  o m*/
 * @param id
 * @return
 * @throws Exception
 */
public boolean deleteRule(int id) throws Exception {
    int brgId = 0;
    String name = "";
    PreparedStatement statement = this.getApexConnection()
            .prepareStatement("SELECT BRG_PROJECTID, NAME FROM BUSINESSRULE WHERE ID=?");
    statement.setInt(1, id);
    ResultSet result = statement.executeQuery();
    while (result.next()) {
        brgId = result.getInt("BRG_PROJECTID");
        name = result.getString("NAME");
    }
    statement.close();
    Statement statementTarget = null;

    try {
        Project project = this.getProject(brgId);
        statementTarget = this.getTargetConnection(project.getTargetConfig()).createStatement();
        statementTarget.executeUpdate("DROP TRIGGER " + name.toUpperCase());
        statementTarget.close();
    } catch (Exception e) {
        Logger log = new Logger();
        log.out(Level.ERROR, "deleteRule", "Rule or project doesn't excist");
    }

    Statement statementRemoveApex = this.getApexConnection().createStatement();
    statementRemoveApex.addBatch("DELETE FROM RULE_COLUMN WHERE BUSINESSRULEID=" + id);
    statementRemoveApex.addBatch("DELETE FROM RULE_TABLE WHERE BUSINESSRULEID=" + id);
    statementRemoveApex.addBatch("DELETE FROM RULE_VALUE WHERE BUSINESSRULEID=" + id);
    statementRemoveApex.addBatch("DELETE FROM BUSINESSRULE WHERE ID=" + id);
    statementRemoveApex.executeBatch();
    statementRemoveApex.close();

    return true;
}

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

private static void LybcOverSpeedRecordsStoreIntoDB(Map<String, PtmOverSpeed> overSpeedRecords,
        ApplicationContext context) {/*from   www. j a  v a2  s . c o m*/
    // INSERT INTO
    // TAB_ALARM_OVERSPEED(LICENCE,BEGIN_TIME,END_TIME,SPEED,IS_END,AREA,MAX_SPEED)
    // SELECT LICENSE,BEGINTIME,ENDTIME,AVGSPEED,'1',FLAG,MAXSPEED FROM
    // ALARMOVERSPEED_REA WHERE BUSINESSTYPE = '3'
    String sql = "";

    Connection conn = null;
    try {
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientLybc");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = overSpeedRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            PtmOverSpeed pos = overSpeedRecords.get(key);
            sql = "insert into TAB_ALARM_OVERSPEED "
                    + " (LICENCE,BEGIN_TIME,END_TIME,SPEED,IS_END,AREA,MAX_SPEED) " + " values ('"
                    + pos.getLicense() + "','" + pos.getBeginTime() + "','" + pos.getEndTIme() + "',"
                    + pos.getAvgSpeed() + "," + "1" + "," + pos.getFlag() + "," + pos.getMaxSpeed() + ")";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB OverSpeed success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        overSpeedRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

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

private static void InOutMoreRecordsStoreIntoDB(Map<String, AlarmMore> iniOutMoreRecords,
        ApplicationContext context) {/*from   w  w w . jav a 2  s. c  o m*/
    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 = iniOutMoreRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            AlarmMore pos = iniOutMoreRecords.get(key);
            sql = "insert into TAB_ALARM_MORE " + " (LICENCE,denoter,fisrt_Time,BEGIN_TIME,END_TIME,road) "
                    + " values (" + "'" + pos.getLicense() + "'," + "'" + pos.getDenoter() + "'," + "'"
                    + pos.getFirstTime() + "'," + "'" + pos.getBeginTime() + "'," + "'" + pos.getEndTime()
                    + "'," + "'" + pos.getRoad() + "')";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB TAB_ALARM_MORE success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        iniOutMoreRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

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

private static void FatigueRecordsStoreIntoDB(Map<String, FatigueAlarmEntity> map, ApplicationContext context) {
    /**/*from  w w  w. ja va2  s  .  c  o m*/
     * INSERT INTO TAB_GPSEVENT_FATIGUE SELECT
     * LICENCE,'',ALARMSTARTTIME,ALARMENDTIME,'' FROM ALARMFATIGUE_REA
     */
    Connection conn = null;
    String sql = "";
    try {
        log.info("--------store Fatigue");
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientDgm");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            FatigueAlarmEntity pos = map.get(key);
            sql = "insert into TAB_GPSEVENT_FATIGUE "
                    + " (license,license_color,start_time,end_time,pointcount) " + " values (" + "'"
                    + pos.getLicence() + "'," + "'" + pos.getLicenceColor() + "'," + "'"
                    + pos.getAlarmStartTime() + "'," + "'" + pos.getAlarmEndTime() + "'," + "'"
                    + pos.getPointCount() + "')";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB FatigueAlarmEntity success!!!]");
    } catch (Exception e) {
        log.info(e);
        log.error(sql);
    } finally {
        DgmAnalysisImp.getInstance().getFatigueMap().clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}