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:com.bluexml.side.Integration.alfresco.sql.synchronization.common.JdbcTransactionListener.java

public int[] executeSQLQuery(List<String> sqlQueries) throws SQLException {
    Connection connection = getConnection();
    Statement st = null;
    int[] rowCount = new int[0];

    // avoid unnecessary processing if there is no queries (opening/closing of a statement) 
    if (!sqlQueries.isEmpty()) {
        try {/*from   w  w w . j  a va  2  s .  c o  m*/
            st = connection.createStatement();
            for (String sqlQuery : sqlQueries) {
                if (logger.isDebugEnabled())
                    logger.debug("[executeSQLQuery(List<String>)] " + sqlQuery);
                st.addBatch(sqlQuery);
            }
            rowCount = st.executeBatch();
            if (logger.isDebugEnabled()) {
                // Just print a log message
                List<String> rowCountAsString = new ArrayList<String>();
                for (int i = 0; i < rowCount.length; i++)
                    rowCountAsString.add(String.format("%1$s", rowCount[i]));
                logger.debug("[executeSQLQuery] Row count: ["
                        + StringUtils.join(rowCountAsString.iterator(), ",") + "]");
            }
        } catch (SQLException e) {
            logger.error("[executeSQLQuery]", e);
            throw (e);
        } finally {
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException e) {
                    logger.error("[executeSQLQuery] cannot close statement ", e);
                }
                st = null;
            }
        }
    }

    return rowCount;
}

From source file:de.forsthaus.h2.My_H2_SampleDataFiller.java

@Override
public void afterPropertiesSet() throws Exception {
    final Logger logger = Logger.getLogger(getClass());
    final Map<Integer, String> allSql = new HashMap<Integer, String>();
    final Connection conn = this.dataSource.getConnection();
    try {//w w w.j  ava  2  s  .  c o m
        // reads the sql-file from the classpath
        final InputStream inputStream = getClass().getResourceAsStream("/createSampleData.sql");
        try {

            final Statement stat = conn.createStatement();

            final BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String str;
            StringBuilder sb = new StringBuilder();
            int count = 0;
            while ((str = in.readLine()) != null) {
                sb.append(str);
                // make a linefeed at each readed line
                if (StringUtils.endsWith(str.trim(), ";")) {
                    final String sql = sb.toString();
                    stat.addBatch(sql);
                    sb = new StringBuilder();
                    allSql.put(Integer.valueOf(count++), sql);
                } else {
                    sb.append("\n");
                }
            }

            final int[] ar = stat.executeBatch();
            final int i = ar.length;

            logger.info("Create DemoData");
            logger.info("count batch updates : " + i);

        } finally {
            try {
                inputStream.close();
            } catch (final IOException e) {
                logger.warn("", e);
            }
        }
    } catch (final BatchUpdateException e) {
        final BatchUpdateException be = e;
        final int[] updateCounts = be.getUpdateCounts();
        if (updateCounts != null) {
            for (int i = 0; i < updateCounts.length; i++) {
                final int j = updateCounts[i];
                if (j < 0) {
                    logger.error("SQL errorcode: " + j + " -> in SQL\n" + allSql.get(Integer.valueOf(i)));
                }
            }
        }
        throw e;
    } finally {
        try {
            conn.close();
        } catch (final SQLException e) {
            logger.warn("", e);
        }
    }
}

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

private static void OverSpeedRecordsStoreIntoDB(Map<String, PtmOverSpeed> overSpeedRecords,
        ApplicationContext context) {//  w w w .  j a v a2s .c o  m
    Connection conn = null;
    String sql = "";
    try {

        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClient1");
        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 ALARMOVERSPEED_REA "
                    + " (CODE,LICENSE,LICENSECOLOR,BEGINTIME,ENDTIME,AVGSPEED,MAXSPEED,FLAG,BUSINESSTYPE) "
                    + " values (" + "'" + pos.getCode() + "'," + "'" + pos.getLicense() + "'," + "'"
                    + pos.getLicenseColor() + "'," + "'" + pos.getBeginTime() + "'," + "'" + pos.getEndTIme()
                    + "'," + pos.getAvgSpeed() + "," + pos.getMaxSpeed() + "," + pos.getFlag() + ","
                    + pos.getBusinessType() + ")";
            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.kpme.core.util.SQLDataLifeCycle.java

public void loadData(final PlatformTransactionManager transactionManager, final DataSource dataSource,
        final String schemaName) {
    LOG.info("Clearing tables for schema " + schemaName);
    Assert.assertNotNull("DataSource could not be located.", dataSource);

    if (schemaName == null || schemaName.equals("")) {
        Assert.fail("Empty schema name given");
    }//  w w w .ja v  a2s . c  o  m
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Object>() {
        public Object doInTransaction(final TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            return new JdbcTemplate(dataSource).execute(new StatementCallback<Object>() {
                public Object doInStatement(Statement statement) throws SQLException {
                    if (callingTestClass != null) {
                        List<String> sqlStatements = getTestDataSQLStatements(
                                "src/test/config/sql/" + callingTestClass.getSimpleName() + ".sql");

                        for (String sql : sqlStatements) {
                            if (!sql.startsWith("#") && !sql.startsWith("//")
                                    && !StringUtils.isEmpty(sql.trim())) {
                                // ignore comment lines in our sql reader.
                                statement.addBatch(sql);
                            }
                        }
                    }
                    statement.executeBatch();
                    return null;
                }
            });
        }
    });
}

From source file:de.tudarmstadt.ukp.csniper.ml.JdbcCustomReader.java

private void query() {
    try {//from  w w  w.j a  v  a 2  s .  c o m
        Statement statement = sqlConnection.createStatement();

        // execute query which sets user variables
        Iterator<String> it = Arrays.asList(StringUtils.split(setterQuery, "\n")).iterator();
        StringBuilder sb = new StringBuilder();
        while (it.hasNext()) {
            String line = it.next();
            if (line.trim().startsWith("#")) {
                continue;
            } else if (line.trim().endsWith(";")) {
                sb.append(line);
                statement.addBatch(sb.toString());
                sb = new StringBuilder();
            } else {
                sb.append(line);
            }
        }
        statement.executeBatch();

        statement.executeQuery(query);
        resultSet = statement.getResultSet();
        resultSet.last();
        resultSetSize = resultSet.getRow();
        resultSet.beforeFirst();
        completed = 0;

        // Store available column names
        columnNames = new HashSet<String>();
        ResultSetMetaData meta = resultSet.getMetaData();
        for (int i = 1; i < meta.getColumnCount() + 1; i++) {
            String columnName = meta.getColumnLabel(i);
            columnNames.add(columnName);
            if (!CAS_COLUMNS.contains(columnName)) {
                getLogger().warn("Unknown column [" + columnName + "].");
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException("There was an unrecoverable error executing the specified SQL statement.",
                e);
    }
}

From source file:com.thinkmore.framework.orm.hibernate.SimpleHibernateDao.java

/**
 * ?/*from www . ja va  2 s .  co m*/
 * @param list sql?
 */
public void executeBatch(final List<String> list) {
    Connection conn = null;
    Statement st = null;
    try {
        conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
        conn.setAutoCommit(false); // ??
        st = conn.createStatement();
        for (int i = 1, j = list.size(); i < j; i++) {
            String sql = list.get(i);
            st.addBatch(sql);
            if (i % 240 == 0) {//?240?sql???
                st.executeBatch();
                conn.commit();
                st.clearBatch();
            } else if (i % j == 0) {//??
                st.executeBatch();
                conn.commit();
                st.clearBatch();
            }
        }
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    } finally {
        closeAll(st, conn);
    }
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsBackendSQL.java

/**
 * {@inheritDoc}/*from  www  .  j a va 2s.  co m*/
 */
public void dbReset(final Connection dbconnection, final String dbResetScript)
        throws SQLException, IOException {
    LOG.info("Running db reset script.");
    Statement stmt = null;
    try {
        stmt = dbconnection.createStatement();
        if (dbResetScript != null) {
            BufferedReader reader = new BufferedReader(new FileReader(dbResetScript));
            String line;
            while ((line = reader.readLine()) != null) {
                stmt.addBatch(line);
            }
        }
        stmt.executeBatch();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsBackendSQL.java

/**
 * {@inheritDoc}/*w  w w.  j ava  2 s.c  om*/
 */
public void dbReset(final Connection dbconnection, final String dbResetScript)
        throws SQLException, IOException {
    LOG.info("Running db reset script.");
    Statement stmt = null;
    BufferedReader reader = null;
    try {
        stmt = dbconnection.createStatement();
        if (dbResetScript != null) {
            reader = new BufferedReader(new FileReader(dbResetScript));
            String line;
            while ((line = reader.readLine()) != null) {
                stmt.addBatch(line);
            }
        }
        stmt.executeBatch();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:xbird.util.jdbc.QueryRunner.java

public int[] batch(Connection conn, String... sqls) throws SQLException {
    final boolean autoCommit = conn.getAutoCommit();
    if (autoCommit) {
        conn.setAutoCommit(false);/*  ww  w. j a  v a  2 s . c  om*/
    }
    Statement stmt = null;
    int[] rows = null;
    try {
        stmt = conn.createStatement();
        for (int i = 0; i < sqls.length; i++) {
            verboseQuery(sqls[i], (Object[]) null);
            stmt.addBatch(sqls[i]);
        }
        rows = stmt.executeBatch();
        conn.commit();
    } catch (SQLException e) {
        DbUtils.rollback(conn);
        rethrow(e, sqls);
    } finally {
        close(stmt);
    }
    // change back commit mode.
    if (autoCommit) {
        conn.setAutoCommit(true);
    }
    return rows;
}

From source file:uk.ac.ebi.bioinvindex.utils.test.DBUnitTest.java

/**
 * Enables/disables the referential integrity checkings in the database.
 *
 * @param isset//www . j  a  v a 2 s.co m
 * @throws SQLException
 */
protected void setReferentialIntegrityCheckings(boolean isset) throws SQLException {

    String sql = null;

    DatabaseMetaData dbmsMeta = connection.getMetaData();
    String dbmsName = dbmsMeta.getDatabaseProductName().toLowerCase();
    String dbmsCatalog = connection.getCatalog();
    if (dbmsCatalog == null)
        // Let's try with the user name
        dbmsCatalog = dbmsMeta.getUserName().toUpperCase();

    log.debug("DBUnitTest.setReferentialIntegrityCheckings(), DBMS Name: '" + dbmsName + "' Catalog: '"
            + dbmsCatalog + "'");

    if (dbmsName.contains("h2"))
        sql = "SET REFERENTIAL_INTEGRITY " + isset;
    else if (dbmsName.contains("mysql"))
        sql = "set FOREIGN_KEY_CHECKS = " + (isset ? "1" : "0");
    else if (dbmsName.contains("oracle")) {
        // Oracle is quite messy...
        String sqlCs = "select css.*, decode(CONSTRAINT_TYPE, 'P', '0', 'C', '1', 'U', 2, 'R', '3', 1000) ctype "
                + "from sys.all_constraints css where owner = '" + dbmsCatalog + "' order by ctype "
                + (isset ? "ASC" : "DESC");

        ResultSet rs = connection.createStatement().executeQuery(sqlCs);
        Statement csDelStmt = connection.createStatement();
        while (rs.next()) {
            String sqlCsCmd = isset ? "enable" : "disable";
            String tbname = rs.getString("TABLE_NAME");
            String csname = rs.getString("CONSTRAINT_NAME");

            String sqlCsDel = "alter table " + dbmsCatalog + "." + tbname + " " + sqlCsCmd + " constraint "
                    + csname;
            log.debug("DBUnitTest, adding sql: " + sqlCsDel);
            csDelStmt.addBatch(sqlCsDel);
        }
        csDelStmt.executeBatch();
        return;
    }

    if (sql == null)
        throw new SQLException(
                "Don't know how to change referential integrity checks for the database: '" + dbmsName + "'");

    connection.createStatement().execute(sql);
}