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.dianping.zebra.shard.jdbc.base.MultiDBBaseTestCase.java

private void createTables() throws Exception {
    Class.forName(getDriverClassName());
    for (MultiCreateTableScriptEntry entry : createdTableList) {
        Connection conn = null;/*www.  j  a  v a 2  s  .  com*/
        Statement stmt = null;
        try {
            conn = DriverManager
                    .getConnection(getDBBaseUrl() + entry.getDbName() + ";MVCC=TRUE;DB_CLOSE_DELAY=-1");
            stmt = conn.createStatement();
            int count = 0;
            for (Map.Entry<String, String> table : entry.getTableNameScriptMapping().entrySet()) {
                stmt.addBatch(table.getValue());
                count++;
            }

            if (count > 0) {
                stmt.executeBatch();
                stmt.clearBatch();
            }
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception e) {

                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {

                }
            }
        }
    }
}

From source file:org.freebxml.omar.server.persistence.rdb.UsageParameterDAO.java

/**
 * Does a bulk insert of a Collection of objects that match the type for this persister.
 *
 *//*www  .  j a v a2 s. co m*/
public void insert(String parentId, List usageParams) throws RegistryException {
    Statement stmt = null;

    if (usageParams.size() == 0) {
        return;
    }

    try {
        stmt = context.getConnection().createStatement();

        Iterator iter = usageParams.iterator();

        while (iter.hasNext()) {
            String value = (String) iter.next();

            String str = "INSERT INTO UsageParameter " + "VALUES( " + "'" + value + "', " + "'" + parentId
                    + "' )";
            log.trace("SQL = " + str);
            stmt.addBatch(str);
        }

        if (usageParams.size() > 0) {
            int[] updateCounts = stmt.executeBatch();
        }
    } catch (SQLException e) {
        RegistryException exception = new RegistryException(e);
        throw exception;
    } finally {
        closeStatement(stmt);
    }
}

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 ww w  .  j  a v a  2 s .co  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:com.dianping.zebra.shard.jdbc.base.MultiDBBaseTestCase.java

@After
public void tearDown() throws Exception {
    Class.forName(getDriverClassName());
    for (MultiCreateTableScriptEntry entry : createdTableList) {
        Connection conn = null;/*from w  w w.  j  av  a2 s  .  c  o  m*/
        Statement stmt = null;
        try {
            conn = DriverManager
                    .getConnection(getDBBaseUrl() + entry.getDbName() + ";MVCC=TRUE;DB_CLOSE_DELAY=-1");
            stmt = conn.createStatement();
            int count = 0;
            for (Map.Entry<String, String> table : entry.getTableNameScriptMapping().entrySet()) {
                stmt.addBatch(" drop table " + table.getKey());
                count++;
            }

            if (count > 0) {
                stmt.executeBatch();
                stmt.clearBatch();
            }
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception e) {

                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception 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  va  2s .com*/
    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:de.tudarmstadt.ukp.dkpro.core.io.jdbc.JdbcReaderExample.java

@Test
public void hsqldbExampleTest() throws SQLException, UIMAException, IOException {
    // Setup in-memory database.
    Connection conn = null;/*from w w w. j  av a  2 s  .c  o  m*/
    Statement stmnt = null;
    try {
        conn = DriverManager.getConnection("jdbc:hsqldb:mem:/" + DB_NAME, DB_USER, DB_PASS);
        stmnt = conn.createStatement();
        stmnt.addBatch("CREATE TABLE " + TBL_NAME + " (title varchar(50), text varchar(100));");
        stmnt.addBatch("INSERT INTO " + TBL_NAME + " (title, text) VALUES ('title1', 'text...1');");
        stmnt.addBatch("INSERT INTO " + TBL_NAME + " (title, text) VALUES ('title2', 'text...2');");
        stmnt.addBatch("INSERT INTO " + TBL_NAME + " (title, text) VALUES ('title3', 'text...3');");
        stmnt.addBatch("INSERT INTO " + TBL_NAME + " (title, text) VALUES ('title4', 'text...4');");
        stmnt.executeBatch();
    } finally {
        DbUtils.closeQuietly(stmnt);
        DbUtils.closeQuietly(conn);
    }
    // Read out with JdbcReader.
    CollectionReader jdbcReader = CollectionReaderFactory.createReader(JdbcReader.class,
            JdbcReader.PARAM_DATABASE, "test_db", JdbcReader.PARAM_USER, "root", JdbcReader.PARAM_PASSWORD, "",
            JdbcReader.PARAM_QUERY, query, JdbcReader.PARAM_DRIVER, "org.hsqldb.jdbc.JDBCDriver",
            JdbcReader.PARAM_CONNECTION, "jdbc:hsqldb:mem:");

    int i = 1;
    while (jdbcReader.hasNext()) {
        // Does it still have a next row?
        jdbcReader.hasNext();
        // Really?
        jdbcReader.hasNext();

        CAS cas = JCasFactory.createJCas().getCas();
        jdbcReader.getNext(cas);
        Assert.assertEquals("title" + i, DocumentMetaData.get(cas).getDocumentTitle());
        Assert.assertEquals("text..." + i, cas.getDocumentText());
        i++;
    }
}

From source file:org.kuali.kpme.core.util.LoadDatabaseDataLifeCycle.java

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

    if (schemaName == null || schemaName.equals("")) {
        Assert.fail("Empty schema name given");
    }//from www. j a  va2  s  .  co 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:it.cnr.icar.eric.server.persistence.rdb.UsageParameterDAO.java

/**
 * Does a bulk insert of a Collection of objects that match the type for this persister.
 *
 *//* www  . j  ava  2 s  . co  m*/
public void insert(String parentId, List<?> usageParams) throws RegistryException {
    Statement stmt = null;

    if (usageParams.size() == 0) {
        return;
    }

    try {
        stmt = context.getConnection().createStatement();

        Iterator<?> iter = usageParams.iterator();

        while (iter.hasNext()) {
            String value = (String) iter.next();

            String str = "INSERT INTO UsageParameter " + "VALUES( " + "'" + value + "', " + "'" + parentId
                    + "' )";
            log.trace("stmt = " + str);
            stmt.addBatch(str);
        }

        if (usageParams.size() > 0) {
            @SuppressWarnings("unused")
            int[] updateCounts = stmt.executeBatch();
        }
    } catch (SQLException e) {
        RegistryException exception = new RegistryException(e);
        throw exception;
    } finally {
        closeStatement(stmt);
    }
}

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

/**
 * {@inheritDoc}// www  . j ava  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.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");
    }//from  ww w .  jav  a2  s.c  om
    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;
                }
            });
        }
    });
}