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.wso2telco.workflow.dao.WorkflowDbService.java

/**
 * Insert operator app endpoints.//from  w w w .j av  a 2s. c o m
 *
 * @param appID            the app id
 * @param opEndpointIDList the op endpoint id list
 * @throws Exception the exception
 */

public void insertOperatorAppEndpoints(int appID, int[] opEndpointIDList)
        throws SQLException, BusinessException {

    Connection con = null;
    Statement st = null;

    try {
        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        log.debug("opEndpointIDList.length : " + opEndpointIDList.length);
        con.setAutoCommit(false);
        st = con.createStatement();
        for (int i = 0; i < opEndpointIDList.length; i++) {
            if (opEndpointIDList[i] > 0 && !endpointAppsIsExist(opEndpointIDList[i], appID)) {
                StringBuilder query = new StringBuilder();
                query.append("INSERT INTO endpointapps (endpointid, applicationid, isactive) VALUES ");
                query.append("(" + opEndpointIDList[i] + "," + appID + ",0)");
                st.addBatch(query.toString());
            }
        }
        st.executeBatch();
        con.commit();

    } catch (SQLException e) {
        throw new SQLException();
    } catch (Exception e) {
        throw new BusinessException(GenaralError.UNDEFINED);
    } finally {
        DbUtils.closeAllConnections(st, con, null);
    }
}

From source file:org.alinous.plugin.derby.DerbyDataSource.java

public void commit(Object connectionHandle, boolean lastAutoCommit, String trxIdentifier)
        throws DataSourceException {
    Connection con = (Connection) connectionHandle;

    Statement batchStmt = this.batchedStatementMap.get(con);
    if (batchStmt != null) {
        try {/* w ww  .  j a  va2  s.co  m*/
            batchStmt.executeBatch();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
            }

            try {
                con.setAutoCommit(lastAutoCommit);
            } catch (SQLException ignore) {
            }

            try {
                batchStmt.close();
            } catch (SQLException e1) {
            }

            // this.batchStmt = null;
            this.batchedStatementMap.remove(con);

            throw new DataSourceException(e);
        }
    }

    try {
        con.commit();
    } catch (SQLException e) {
        throw new DataSourceException(e);
    } finally {
        try {
            batchStmt.close();
        } catch (SQLException e1) {
        }

        try {
            con.setAutoCommit(lastAutoCommit);
        } catch (SQLException ignore) {
        }

        this.batchedStatementMap.remove(con);
    }
}

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

/**
 * Resets the database./*from   w ww .  ja va2s . c  o  m*/
 * 
 * @throws SQLException
 *             If something goes wrong resetting the database.
 * @throws IOException
 *             If something goes wrong reading the reset script.
 * @throws UnsupportedOperationsException
 *             If database resets are not allowed.
 */
public void doDbReset() throws SQLException, IOException {
    if (dbResetAllowed) {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
                Connection connection = session.connection();
                LOG.info("Running db reset script from file " + dbResetScript);
                Statement stmt = connection.createStatement();
                BufferedReader reader = new BufferedReader(new FileReader(dbResetScript));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (!line.startsWith("--")) {
                        LOG.debug("SQL: " + line);
                        stmt.addBatch(line);
                    }
                }
                stmt.executeBatch();
                tx.commit();
            } catch (Exception e) {
                LOG.error("dbReset failed: " + e.toString(), e);
                if (tx != null) {
                    tx.rollback();
                }
                throw new SQLException(e.toString());
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    } else {
        throw new UnsupportedOperationException();
    }
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testTransaction()
        throws SQLException, IOException, ZooKeeperConnectionException, InterruptedException {
    stat.execute(DruidParserTestUtil.SEED[0]);
    TEST_UTIL.waitTableAvailable(Bytes.toBytes("User"));
    stat.execute(DruidParserTestUtil.SEED[1]);
    TEST_UTIL.waitTableAvailable(Bytes.toBytes("Photo"));

    conn.setAutoCommit(false);/*from  ww w.  j  a v  a2s  .  com*/
    Statement stat = conn.createStatement();
    stat.addBatch("Insert into User(user_id,name) values(1,'testTransaction');");
    stat.addBatch("Insert into Photo(user_id,photo_id,tag) values(1,1,'tag');");
    int[] ret = stat.executeBatch();
    conn.commit();
    int successNum = 0;
    for (int i : ret) {
        if (i == 1)
            successNum++;
    }
    assertTrue(successNum == 2);

    ResultSet rs = stat.executeQuery("SELECT * FROM User WHERE user_id=1");
    assertTrue(rs.next());
    assertTrue(rs.getString("name").equals("testTransaction"));

    rs = stat.executeQuery("SELECT * FROM Photo WHERE user_id=1 and photo_id=1");
    assertTrue(rs.next());
    assertTrue(rs.getString("tag").equals("tag"));

}

From source file:org.apache.tajo.catalog.store.DBStore.java

@Override
public final void addTable(final TableDesc table) throws IOException {
    Statement stmt = null;
    ResultSet res;//  w ww .  java  2  s  .co  m

    String sql = "INSERT INTO " + TB_TABLES + " (" + C_TABLE_ID + ", path, store_type) " + "VALUES('"
            + table.getId() + "', " + "'" + table.getPath() + "', " + "'" + table.getMeta().getStoreType() + "'"
            + ")";

    wlock.lock();
    try {
        stmt = conn.createStatement();
        if (LOG.isDebugEnabled()) {
            LOG.debug(sql);
        }
        stmt.addBatch(sql);
        stmt.executeBatch();

        stmt = conn.createStatement();
        sql = "SELECT TID from " + TB_TABLES + " WHERE " + C_TABLE_ID + " = '" + table.getId() + "'";
        if (LOG.isDebugEnabled()) {
            LOG.debug(sql);
        }
        res = stmt.executeQuery(sql);
        if (!res.next()) {
            throw new IOException("ERROR: there is no tid matched to " + table.getId());
        }
        int tid = res.getInt("TID");

        String colSql;
        int columnId = 0;
        for (Column col : table.getMeta().getSchema().getColumns()) {
            colSql = columnToSQL(tid, table, columnId, col);
            if (LOG.isDebugEnabled()) {
                LOG.debug(colSql);
            }
            stmt.addBatch(colSql);
            columnId++;
        }

        Iterator<Entry<String, String>> it = table.getMeta().getOptions();
        String optSql;
        while (it.hasNext()) {
            optSql = keyvalToSQL(table, it.next());
            if (LOG.isDebugEnabled()) {
                LOG.debug(optSql);
            }
            stmt.addBatch(optSql);
        }
        stmt.executeBatch();
        if (table.getMeta().getStat() != null) {
            sql = "INSERT INTO " + TB_STATISTICS + " (" + C_TABLE_ID + ", num_rows, num_bytes) " + "VALUES ('"
                    + table.getId() + "', " + table.getMeta().getStat().getNumRows() + ","
                    + table.getMeta().getStat().getNumBytes() + ")";
            if (LOG.isDebugEnabled()) {
                LOG.debug(sql);
            }
            stmt.addBatch(sql);
            stmt.executeBatch();
        }
    } catch (SQLException se) {
        throw new IOException(se.getMessage(), se);
    } finally {
        wlock.unlock();
        try {
            stmt.close();
        } catch (SQLException e) {
        }
    }
}

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

/**
 * Does a bulk delete of a Collection of objects that match the type for this persister.
 *
 *///w w w . j  a va  2  s .c  om
public void delete(List objects) throws RegistryException {
    //Return immediatley if no objects to insert
    if (objects.size() == 0) {
        return;
    }

    log.trace(ServerResourceBundle.getInstance().getString("message.DeletingRowsInTable",
            new Object[] { new Integer(objects.size()), getTableName() }));
    action = DAO_ACTION_DELETE;

    Statement stmt = null;

    try {
        stmt = context.getConnection().createStatement();
        Iterator iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            prepareToDelete(obj);

            String str = getSQLStatementFragment(obj);
            log.trace("SQL = " + str);
            stmt.addBatch(str);

            // HIEOS/BHT (Added block to get rid of MySQL performance bug with DB views).
            String mirrorImageStr = this.getSQLStatementFragmentForMirrorImage(obj);
            if (mirrorImageStr != null) {
                log.trace("SQL = " + mirrorImageStr); // HIEOS/BHT (DEBUG)
                stmt.addBatch(mirrorImageStr); // Now, DELETE the mirror.
            }
        }

        int[] updateCounts = stmt.executeBatch();

        iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            onDelete(obj);
        }

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(stmt);
    }
}

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

/**
 * @see org.freebxml.omar.server.persistence.rdb.OMARDAO#update(org.oasis.ebxml.registry.bindings.rim.UserType, java.sql.Connection, java.util.List, java.util.HashMap)
 *///from  w  w w .  j  a v  a2 s  .  c  o m
public void update(List objects) throws RegistryException {

    //Return immediatley if no objects to insert
    if (objects.size() == 0) {
        return;
    }

    log.trace(ServerResourceBundle.getInstance().getString("message.UpdatingRowsInTable",
            new Object[] { new Integer(objects.size()), getTableName() }));
    action = DAO_ACTION_UPDATE;

    Statement stmt = null;

    try {
        stmt = context.getConnection().createStatement();
        Iterator iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            prepareToUpdate(obj);

            String str = getSQLStatementFragment(obj);
            log.trace("SQL = " + str);
            stmt.addBatch(str);

            // HIEOS/BHT (Added block to get rid of MySQL performance bug with DB views).
            String mirrorImageStr = this.getSQLStatementFragmentForMirrorImage(obj);
            if (mirrorImageStr != null) {
                log.trace("SQL = " + mirrorImageStr); // HIEOS/BHT (DEBUG)
                stmt.addBatch(mirrorImageStr); // Now, update the mirror.
            }
        }

        int[] updateCounts = stmt.executeBatch();

        iter = objects.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();

            onUpdate(obj);
        }

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(stmt);
    }
}

From source file:com.flexive.ejb.beans.BriefcaseEngineBean.java

/**
 * {@inheritDoc}/* w w w. j a v a  2  s  . c o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void remove(long id) throws FxApplicationException {
    // Lookup the briefcase
    Briefcase br = load(id);
    if (br == null) {
        throw new FxNotFoundException("ex.briefcase.notFound", ("#" + id));
    }
    // Permission checks
    final UserTicket ticket = FxContext.getUserTicket();
    if (!ticket.isGlobalSupervisor() && br.getMandator() != ticket.getMandatorId()) {
        if (!ticket.mayDeleteACL(br.getAcl(), br.getLifeCycleInfo().getCreatorId())) {
            throw new FxNotFoundException("ex.briefcase.noDeletePermission", br.getName());
        }
    }
    // Delete operation
    Connection con = null;
    Statement stmt = null;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();
        stmt = con.createStatement();
        stmt.addBatch("DELETE FROM " + TBL_BRIEFCASE_DATA_ITEM + " WHERE briefcase_id=" + id);
        stmt.addBatch("DELETE FROM " + TBL_BRIEFCASE_DATA + " WHERE briefcase_id=" + id);
        stmt.addBatch("DELETE FROM " + DatabaseConst.TBL_BRIEFCASE + " WHERE id=" + id);
        stmt.executeBatch();
    } catch (SQLException exc) {
        throw new FxRemoveException(LOG, exc, "ex.briefcase.deleteFailed", br.getName());
    } finally {
        closeObjects(BriefcaseEngineBean.class, con, stmt);
    }
}

From source file:dao.RuleDao.java

/**
 * Create a new rule based on incoming NewRule class
 * /* w  w w.  ja  va  2  s . c o  m*/
 * @param rule
 * @return
 * @throws SQLException
 */
public boolean createRule(NewRule rule) throws SQLException {
    Logger log = new Logger();
    log.out(Level.INFORMATIVE, "createRule", "Start making rules");
    Statement statement = this.getApexConnection().createStatement();

    statement.addBatch("DELETE RULE_COLUMN WHERE BUSINESSRULEID=" + rule.getBusinessrule());
    statement.addBatch("DELETE RULE_VALUE WHERE BUSINESSRULEID=" + rule.getBusinessrule());
    statement.addBatch("DELETE RULE_TABLE WHERE BUSINESSRULEID=" + rule.getBusinessrule());

    if (rule.getColumns() != null) {
        for (String column : rule.getColumns()) {
            statement.addBatch("INSERT INTO RULE_COLUMN (NAME, BUSINESSRULEID) VALUES ('" + column + "', '"
                    + rule.getBusinessrule() + "')");
        }
    } else {
        log.out(Level.ERROR, "createRule", "No columns found");
    }
    if (rule.getValues() != null) {
        for (String value : rule.getValues()) {
            statement.addBatch("INSERT INTO RULE_VALUE (NAME, BUSINESSRULEID) VALUES ('" + value + "', '"
                    + rule.getBusinessrule() + "')");
        }
    } else {
        log.out(Level.ERROR, "createRule", "No values found");
    }
    if (rule.getTables() != null) {
        for (String table : rule.getTables()) {
            statement.addBatch("INSERT INTO RULE_TABLE (NAME, BUSINESSRULEID) VALUES ('" + table + "', '"
                    + rule.getBusinessrule() + "')");
        }
    } else {
        log.out(Level.ERROR, "createRule", "No tables found");
    }
    statement.executeBatch();
    statement.close();
    return true;
}

From source file:org.hyperic.hq.events.server.session.RegisteredTriggerManagerImpl.java

@PostConstruct
public void cleanupRegisteredTriggers() {
    Connection conn = null;/*from   w ww .  j  a  v a 2s. c  o  m*/
    Statement stmt = null;
    Boolean autocommit = null;
    boolean commit = false;
    try {
        conn = dbUtil.getConnection();
        autocommit = Boolean.valueOf(conn.getAutoCommit());
        conn.setAutoCommit(false);
        stmt = conn.createStatement();
        stmt.addBatch("update EAM_ALERT_CONDITION set trigger_id = null " + "WHERE exists ("
                + "select 1 from EAM_ALERT_DEFINITION WHERE deleted = '1' "
                + "AND EAM_ALERT_CONDITION.alert_definition_id = id" + ")");
        stmt.addBatch("delete from EAM_REGISTERED_TRIGGER WHERE exists ("
                + "select 1 from EAM_ALERT_DEFINITION WHERE deleted = '1' "
                + "AND EAM_REGISTERED_TRIGGER.alert_definition_id = id" + ")");
        int[] rows = stmt.executeBatch();
        conn.commit();
        commit = true;
        log.info("disassociated " + rows[0] + " triggers in EAM_ALERT_CONDITION"
                + " from their deleted alert definitions");
        log.info("deleted " + rows[1] + " rows from EAM_REGISTERED_TRIGGER");
    } catch (SQLException e) {
        log.error(e, e);
    } finally {
        resetAutocommit(conn, autocommit);
        if (!commit)
            rollback(conn);
        DBUtil.closeJDBCObjects(RegisteredTriggerManagerImpl.class.getName(), conn, stmt, null);
    }
}