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:net.big_oh.common.jdbc.JdbcProxyExerciser.java

private static void exerciseBatchInsert(Connection con) throws SQLException {
    logger.info(StringUtils.center("exercise batch insert", 100, "-"));

    Statement stmt = null;
    try {/*  ww  w  .ja v a2s .  c  o  m*/
        stmt = con.createStatement();
        stmt.addBatch("INSERT INTO TEST_TABLE VALUES ( 'value2' )");
        stmt.addBatch("INSERT INTO TEST_TABLE VALUES ( 'value3' )");
        stmt.executeBatch();
    } finally {
        DbUtils.closeQuietly(stmt);
    }
}

From source file:org.diffkit.util.DKSqlUtil.java

public static long executeBatchUpdate(List<String> sqlUpdateStrings_, Connection connection_) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("sqlUpdateStrings_: " + sqlUpdateStrings_.size());
        LOG.debug("connection_: " + connection_);
    }//from   w  w w. j  a  va2 s .c  o m
    DKValidate.notNull(connection_);
    if ((sqlUpdateStrings_ == null) || (sqlUpdateStrings_.size() == 0))
        return 0;

    Statement statement = null;
    int[] rowCounts = null;
    try {
        statement = connection_.createStatement();
        for (String sqlUpdate : sqlUpdateStrings_)
            statement.addBatch(sqlUpdate);

        rowCounts = statement.executeBatch();
        if (LOG.isDebugEnabled())
            LOG.debug("effectedRowCount: " + ArrayUtils.toString(rowCounts));

    } catch (Exception e_) {
        LOG.warn(null, e_);
        if (DKObjectUtil.respondsTo(e_, "getNextException", null)) {
            try {
                Exception nextException = (Exception) DKObjectUtil.invoke(e_, "getNextException", null);
                LOG.warn(null, nextException);
            } catch (Exception f_) {
                LOG.error(null, f_);
            }
        }
        rollback(connection_);
    } finally {
        close(statement);
    }

    return DKArrayUtil.sum(rowCounts);
}

From source file:com.laudandjolynn.mytv.Main.java

/**
 * ???//from w  ww .  jav a  2s .c o m
 */
private static void initDbData0(MyTvData data) {
    if (data.isDataInited()) {
        logger.info("init data had insert into db.");
        return;
    }
    Properties tvStationProp = new Properties();
    try {
        tvStationProp.load(Main.class.getResourceAsStream("/" + Constant.TV_STATION_INIT_DATA_FILE_NAME));
    } catch (IOException e) {
        throw new MyTvException(
                "error occur while load property file: " + Constant.TV_STATION_INIT_DATA_FILE_NAME, e);
    }

    Collection<Object> values = tvStationProp.values();
    List<String> insertSqlList = new ArrayList<String>(values.size());
    String insertSql = "insert into my_tv (stationName,displayName,classify,channel,sequence)";
    for (Object value : values) {
        insertSqlList.add(insertSql + " values (" + value.toString() + ")");
    }

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DataSourceManager.getConnection();
        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        for (String sql : insertSqlList) {
            stmt.addBatch(sql);
            logger.info("execute sql: " + sql);
        }
        stmt.executeBatch();
        conn.commit();
        data.writeData(null, Constant.XML_TAG_DATA, "true");
    } catch (SQLException e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new MyTvException("error occur while rollback transaction.", e1);
            }
        }
        throw new MyTvException("error occur while execute sql on db.", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new MyTvException("error occur while close statement.", e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new MyTvException("error occur while close sqlite connection.", e);
            }
        }
    }

}

From source file:com.laudandjolynn.mytv.Main.java

/**
 * ??/*from w  w  w . j a  v  a 2 s .c  o  m*/
 */
private static void initDb(MyTvData data) {
    if (data.isDbInited()) {
        logger.debug("db have already init.");
        return;
    }

    File myTvDataFilePath = new File(Constant.MY_TV_DATA_FILE_PATH);
    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DataSourceManager.getConnection();
        conn.setAutoCommit(false);
        stmt = conn.createStatement();
        List<String> sqlList = loadSql();
        for (String sql : sqlList) {
            stmt.addBatch(sql);
            logger.info("execute sql: " + sql);
        }
        stmt.executeBatch();
        conn.commit();
        DataSourceManager.DATA_SOURCE_PROP.remove(DataSourceManager.RES_KEY_DB_SQL_LIST);
        data.writeData(null, Constant.XML_TAG_DB, "true");
    } catch (SQLException e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new MyTvException("error occur while rollback transaction.", e);
            }
        }
        myTvDataFilePath.deleteOnExit();
        throw new MyTvException("error occur while execute sql on db.", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new MyTvException("error occur while close statement.", e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new MyTvException("error occur while close sqlite connection.", e);
            }
        }
    }
}

From source file:gridool.util.jdbc.JDBCUtils.java

public static int[] batch(Connection conn, String... sqls) throws SQLException {
    final boolean autoCommit = conn.getAutoCommit();
    if (autoCommit) {
        conn.setAutoCommit(false);/* w w w .j a  va2  s .c  o m*/
    }
    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) {
        conn.rollback();
        rethrow(e, sqls);
    } finally {
        close(stmt);
    }
    // change back commit mode.
    if (autoCommit) {
        conn.setAutoCommit(true);
    }
    return rows;
}

From source file:org.n52.sos.ds.hibernate.H2Configuration.java

public static void recreate() {
    synchronized (LOCK) {
        if (instance == null) {
            throw new IllegalStateException("Database is not initialized");
        }// ww w  .  ja v a 2  s .  c om
        Session session = null;
        Transaction transaction = null;
        try {
            session = getSession();
            transaction = session.beginTransaction();
            session.doWork(new Work() {
                @Override
                public void execute(final Connection connection) throws SQLException {
                    Statement stmt = null;
                    try {
                        stmt = connection.createStatement();
                        for (final String cmd : instance.getDropScript()) {
                            stmt.addBatch(cmd);
                        }
                        for (final String cmd : instance.getCreateScript()) {
                            stmt.addBatch(cmd);
                        }
                        stmt.executeBatch();
                    } finally {
                        if (stmt != null) {
                            stmt.close();
                        }
                    }
                }
            });
            transaction.commit();
        } catch (final HibernateException e) {
            if (transaction != null) {
                transaction.rollback();
            }
            throw e;
        } finally {
            returnSession(session);
        }
    }
}

From source file:org.n52.sos.ds.hibernate.H2Configuration.java

public static void truncate() {
    synchronized (LOCK) {
        if (instance == null) {
            throw new IllegalStateException("Database is not initialized");
        }/*from   w w  w.j  a va 2  s . c o  m*/
        final Iterator<Table> tableMappings = instance.getConfiguration().getTableMappings();
        final List<String> tableNames = new LinkedList<String>();
        GeoDBDialect dialect = new GeoDBDialect();
        while (tableMappings.hasNext()) {
            tableNames.add(tableMappings.next().getQuotedName(dialect));
        }
        Session session = null;
        Transaction transaction = null;
        try {
            session = getSession();
            transaction = session.beginTransaction();
            session.doWork(new Work() {
                @Override
                public void execute(final Connection connection) throws SQLException {
                    Statement stmt = null;
                    try {
                        stmt = connection.createStatement();
                        stmt.addBatch("SET REFERENTIAL_INTEGRITY FALSE");
                        for (final String table : tableNames) {
                            stmt.addBatch("DELETE FROM " + table);
                        }
                        stmt.addBatch("SET REFERENTIAL_INTEGRITY TRUE");
                        stmt.executeBatch();
                    } finally {
                        if (stmt != null) {
                            stmt.close();
                        }
                    }
                }
            });
            transaction.commit();
        } catch (final HibernateException e) {
            if (transaction != null) {
                transaction.rollback();
            }
            throw e;
        } finally {
            returnSession(session);
        }
    }
}

From source file:org.apache.drill.exec.store.http.util.DBUtil.java

private static void insertTestData(Statement statement, String table, int keyFrom, int keyTo, Connection conn)
        throws SQLException {

    String initSql = "insert into " + table + "(id, name, sex, code, score) values";
    StringBuffer insertSqlSb = new StringBuffer(initSql);

    // int batchCount=100;
    for (int i = keyFrom; i <= keyTo; i++) {

        insertSqlSb.append("(");
        insertSqlSb.append(i + ", ");
        insertSqlSb.append("'Tom" + (i % 100) + "', ");
        insertSqlSb.append((i % 2) + ", ");
        insertSqlSb.append(i % 1000 + ", ");
        insertSqlSb.append(i * 10000);// ww w  . j  av  a2s .co m
        insertSqlSb.append(")");

        if (i % batch_insert_count == 0) {
            statement.addBatch(insertSqlSb.toString());
            statement.executeBatch();
            //conn.commit();  
            insertSqlSb = new StringBuffer(initSql);
        } else {

            insertSqlSb.append(",");
        }

    }

}

From source file:org.sipfoundry.sipxconfig.admin.dialplan.sbc.SbcMigrationContextImpl.java

private void cleanSchema() {
    try {/*from  ww  w . j a v a  2  s.com*/
        Session currentSession = getHibernateTemplate().getSessionFactory().getCurrentSession();
        Connection connection = currentSession.connection();
        Statement statement = connection.createStatement();
        statement.addBatch(SQL);
        statement.executeBatch();
        statement.close();
    } catch (SQLException e) {
        LOG.warn("cleaning schema", e);
    }
}

From source file:com.hangum.tadpole.rdb.core.editors.main.execute.sub.ExecuteBatchSQL.java

/**
 * select? execute  .//w w  w .  jav  a  2s  .  co  m
 * @param errMsg 
 * 
 * @param listQuery
 * @param reqQuery
 * @param userDB
 * @param userType
 * @param intCommitCount
 * @param userEmail
 * @throws Exception
 */
public static void runSQLExecuteBatch(String errMsg, List<String> listQuery, final RequestQuery reqQuery,
        final UserDBDAO userDB, final String userType, final int intCommitCount, final String userEmail)
        throws Exception {
    if (!PermissionChecker.isExecute(userType, userDB, listQuery)) {
        throw new Exception(errMsg);
    }
    // Check the db access control 
    for (String strQuery : listQuery) {
        if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getDdl_lock())) {
            throw new Exception(errMsg);
        }

        PublicTadpoleDefine.QUERY_DML_TYPE queryType = SQLUtil.sqlQueryType(strQuery);
        if (reqQuery.getSqlType() == SQL_TYPE.DDL) {
            if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getDdl_lock())) {
                throw new Exception(errMsg);
            }
        }
        if (queryType == QUERY_DML_TYPE.INSERT) {
            if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getInsert_lock())) {
                throw new Exception(errMsg);
            }
        }
        if (queryType == QUERY_DML_TYPE.UPDATE) {
            if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getUpdate_lock())) {
                throw new Exception(errMsg);
            }
        }
        if (queryType == QUERY_DML_TYPE.DELETE) {
            if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getDelete_locl())) {
                throw new Exception(errMsg);
            }
        }
    }

    java.sql.Connection javaConn = null;
    Statement statement = null;

    try {
        if (reqQuery.isAutoCommit()) {
            SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
            javaConn = client.getDataSource().getConnection();
        } else {
            javaConn = TadpoleSQLTransactionManager.getInstance(userEmail, userDB);
        }
        statement = javaConn.createStatement();

        int count = 0;
        for (String strQuery : listQuery) {
            //  ? commit? rollback?    ???
            if (!TransactionManger.calledCommitOrRollback(reqQuery.getSql(), userEmail, userDB)) {

                if (StringUtils.startsWithIgnoreCase(strQuery.trim(), "CREATE TABLE")) { //$NON-NLS-1$
                    strQuery = StringUtils.replaceOnce(strQuery, "(", " ("); //$NON-NLS-1$ //$NON-NLS-2$
                }

            }
            statement.addBatch(strQuery);

            if (++count % intCommitCount == 0) {
                statement.executeBatch();
                count = 0;
            }
        }
        statement.executeBatch();
    } catch (Exception e) {
        logger.error("Execute batch update", e); //$NON-NLS-1$
        throw e;
    } finally {
        try {
            statement.close();
        } catch (Exception e) {
        }

        if (reqQuery.isAutoCommit()) {
            try {
                javaConn.close();
            } catch (Exception e) {
            }
        }
    }
}