Example usage for java.sql PreparedStatement addBatch

List of usage examples for java.sql PreparedStatement addBatch

Introduction

In this page you can find the example usage for java.sql PreparedStatement addBatch.

Prototype

void addBatch() throws SQLException;

Source Link

Document

Adds a set of parameters to this PreparedStatement object's batch of commands.

Usage

From source file:org.wso2.carbon.apimgt.migration.client.MigrateFrom110to200.java

private void updateIdnAccessToken(PreparedStatement accessTokenUpdate, ConsumerKeyDTO consumerKeyDTO)
        throws SQLException {
    accessTokenUpdate.setString(1, consumerKeyDTO.getDecryptedConsumerKey());
    accessTokenUpdate.setString(2, consumerKeyDTO.getEncryptedConsumerKey());
    accessTokenUpdate.addBatch();
}

From source file:com.wso2telco.dep.mediator.dao.USSDDAO.java

public void moUssdSubscriptionEntry(List<OperatorSubscriptionDTO> domainsubs, Integer moSubscriptionId)
        throws SQLException, Exception {

    Connection con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
    PreparedStatement insertStatement = null;

    try {//from   w ww .  j  av a2s . c om

        if (con == null) {
            throw new Exception("Connection not found");
        }
        con.setAutoCommit(false);

        StringBuilder queryString = new StringBuilder("INSERT INTO ");
        queryString.append(DatabaseTables.MO_USSD_SUBSCRIPTIONS.getTableName());
        queryString.append(" (ussd_request_did, domainurl, operator) ");
        queryString.append("VALUES (?, ?, ?)");

        insertStatement = con.prepareStatement(queryString.toString());

        for (OperatorSubscriptionDTO d : domainsubs) {

            insertStatement.setInt(1, moSubscriptionId);
            insertStatement.setString(2, d.getDomain());
            insertStatement.setString(3, d.getOperator());

            insertStatement.addBatch();
        }

        insertStatement.executeBatch();
        con.commit();

    } catch (SQLException e) {

        log.error("database operation error in operatorSubsEntry : ", e);
        throw e;
    } catch (Exception e) {

        log.error("error in operatorSubsEntry : ", e);
        throw e;
    } finally {

        DbUtils.closeAllConnections(insertStatement, con, null);
    }
}

From source file:com.ibm.bluemix.samples.PostgreSQLClient.java

/**
 * Insert text into PostgreSQL/*from  w  ww.ja v  a  2s.c om*/
 * 
 * param posts List of Strings of text to insert
 * 
 * @return number of rows affected
 * @throws Exception
 * @throws Exception
 */
public int addPosts(List<String> posts) throws Exception {
    String sql = "INSERT INTO posts (text) VALUES (?)";
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = getConnection();
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(sql);

        for (String s : posts) {
            statement.setString(1, s);
            statement.addBatch();
        }
        int[] rows = statement.executeBatch();
        connection.commit();

        return rows.length;
    } catch (SQLException e) {
        SQLException next = e.getNextException();

        if (next != null) {
            throw next;
        }

        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }

        if (connection != null) {
            connection.close();
        }
    }
}

From source file:net.solarnetwork.node.dao.jdbc.reactor.JdbcInstructionDao.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public Long storeInstruction(final Instruction instruction) {
    // first store our Instruction entity
    final Long pk = storeDomainObject(instruction, getSqlResource(RESOURCE_SQL_INSERT_INSTRUCTION));

    // now store all the Instruction's parameters
    getJdbcTemplate().execute(new PreparedStatementCreator() {

        @Override//from www  .  j  a  v  a 2s.  co  m
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(getSqlResource(RESOURCE_SQL_INSERT_INSTRUCTION_PARAM));
            return ps;
        }
    }, new PreparedStatementCallback<Object>() {

        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            int pos = 0;
            for (String paramName : instruction.getParameterNames()) {
                String[] paramValues = instruction.getAllParameterValues(paramName);
                if (paramValues == null || paramValues.length < 1) {
                    continue;
                }
                for (String paramValue : paramValues) {
                    int col = 1;
                    ps.setLong(col++, pk);
                    ps.setLong(col++, pos);
                    ps.setString(col++, paramName);
                    ps.setString(col++, paramValue);
                    ps.addBatch();
                    pos++;
                }
            }
            int[] batchResults = ps.executeBatch();
            if (log.isTraceEnabled()) {
                log.trace("Batch inserted {} instruction params: {}", pos, Arrays.toString(batchResults));
            }
            return null;
        }
    });

    // finally crate a status row
    Date statusDate = new Date();
    getJdbcTemplate().update(getSqlResource(RESOURCE_SQL_INSERT_INSTRUCTION_STATUS), pk,
            new java.sql.Timestamp(statusDate.getTime()), InstructionState.Received.toString());
    return pk;
}

From source file:org.wso2.carbon.device.mgt.core.dao.impl.ApplicationMappingDAOImpl.java

@Override
public void addApplicationMappingsWithApps(int deviceId, int enrolmentId, List<Application> applications,
        int tenantId) throws DeviceManagementDAOException {

    Connection conn;/*  www  . ja  va 2 s  .c  o m*/
    PreparedStatement stmt = null;
    ResultSet rs = null;
    ByteArrayOutputStream bao = null;
    ObjectOutputStream oos = null;

    try {
        conn = this.getConnection();
        String sql = "INSERT INTO DM_DEVICE_APPLICATION_MAPPING (DEVICE_ID, ENROLMENT_ID, APPLICATION_ID, "
                + "APP_PROPERTIES, MEMORY_USAGE, IS_ACTIVE, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?)";

        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(sql);

        for (Application application : applications) {
            stmt.setInt(1, deviceId);
            stmt.setInt(2, enrolmentId);
            stmt.setInt(3, application.getId());

            bao = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bao);
            oos.writeObject(application.getAppProperties());
            stmt.setBytes(4, bao.toByteArray());

            stmt.setInt(5, application.getMemoryUsage());
            stmt.setBoolean(6, application.isActive());

            stmt.setInt(7, tenantId);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (SQLException e) {
        throw new DeviceManagementDAOException("Error occurred while adding device application mappings", e);
    } catch (IOException e) {
        throw new DeviceManagementDAOException("Error occurred while serializing application properties object",
                e);
    } finally {
        if (bao != null) {
            try {
                bao.close();
            } catch (IOException e) {
                log.error("Error occurred while closing ByteArrayOutputStream", e);
            }
        }
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException e) {
                log.error("Error occurred while closing ObjectOutputStream", e);
            }
        }
        DeviceManagementDAOUtil.cleanupResources(stmt, rs);
    }

}

From source file:com.flexive.ejb.beans.structure.SelectListEngineBean.java

/**
 * Update the positions of all items//from  w  w  w. ja v a  2 s  . c om
 *
 * @param items select list items
 * @param idMap map of ids for new created items
 * @throws FxApplicationException on errors
 */
private void updatePositions(List<FxSelectListItem> items, Map<Long, Long> idMap)
        throws FxApplicationException {
    Connection con = null;
    PreparedStatement ps = null;
    int pos = 0;
    try {
        con = Database.getDbConnection();
        //                                                                    1          2
        ps = con.prepareStatement("UPDATE " + TBL_STRUCT_SELECTLIST_ITEM + " SET POS=? WHERE ID=?");
        for (FxSelectListItem item : items) {
            ps.setInt(1, pos++);
            ps.setLong(2,
                    item.getId() < 0 && idMap != null
                            ? (idMap.containsKey(item.getId()) ? idMap.get(item.getId()) : -1)
                            : item.getId());
            ps.addBatch();
        }
        ps.executeBatch();
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(TypeEngineBean.class, con, ps);
    }
}

From source file:org.wso2.carbon.is.migration.service.v510.migrator.UMDataMigrator.java

public void migrateUMData() throws MigrationClientException {
    log.info("MIGRATION-LOGS >> Going to start : migrateUMData.");
    Connection identityConnection = null;
    Connection umConnection = null;

    PreparedStatement selectServiceProviders = null;
    PreparedStatement updateRole = null;

    ResultSet selectServiceProvidersRS = null;

    try {//from ww w.j ava2 s. c  o  m
        identityConnection = getDataSource(Schema.IDENTITY.getName()).getConnection();
        umConnection = getDataSource().getConnection();

        identityConnection.setAutoCommit(false);
        umConnection.setAutoCommit(false);

        selectServiceProviders = identityConnection.prepareStatement(SQLQueries.LOAD_APP_NAMES);
        selectServiceProvidersRS = selectServiceProviders.executeQuery();

        updateRole = umConnection.prepareStatement(SQLQueries.UPDATE_ROLES);
        while (selectServiceProvidersRS.next()) {
            try {
                String appName = selectServiceProvidersRS.getString("APP_NAME");
                int tenantId = selectServiceProvidersRS.getInt("TENANT_ID");
                updateRole.setString(1,
                        ApplicationConstants.APPLICATION_DOMAIN + UserCoreConstants.DOMAIN_SEPARATOR + appName);
                updateRole.setString(2, appName);
                updateRole.setInt(3, tenantId);
                if (isBatchUpdate()) {
                    updateRole.addBatch();
                } else {
                    updateRole.executeUpdate();
                    log.info("MIGRATION-LOGS >> Executed query : " + updateRole.toString());
                }
            } catch (Exception e) {
                log.error("MIGRATION-ERROR-LOGS-037 >> Error while executing the migration.", e);
                if (!isContinueOnError()) {
                    throw new MigrationClientException("Error while executing the migration.", e);
                }
            }
        }
        if (isBatchUpdate()) {
            updateRole.executeBatch();
            log.info("MIGRATION-LOGS >> Executed query : " + updateRole.toString());
        }
        identityConnection.commit();
        umConnection.commit();
    } catch (SQLException e) {
        log.error("MIGRATION-ERROR-LOGS-038 >> Error while executing the migration.", e);
        if (!isContinueOnError()) {
            throw new MigrationClientException("Error while executing the migration.", e);
        }
    } finally {
        try {
            IdentityDatabaseUtil.closeResultSet(selectServiceProvidersRS);
            IdentityDatabaseUtil.closeStatement(selectServiceProviders);
            IdentityDatabaseUtil.closeStatement(updateRole);
            IdentityDatabaseUtil.closeConnection(identityConnection);
            IdentityDatabaseUtil.closeConnection(umConnection);
        } catch (Exception e) {

        }
    }
    log.info("MIGRATION-LOGS >> Done : migrateUMData.");
}

From source file:com.pactera.edg.am.metamanager.extractor.dao.helper.CreateCompositionHelper.java

private void doInPreparedStatement(MMMetaModel metaModel, PreparedStatement ps) throws SQLException {
    List<AbstractMetadata> metadatas = metaModel.getMetadatas();
    String parentMetaModelId = metaModel.getParentMetaModel().getCode();
    String metaModelId = metaModel.getCode();
    String relationshipName = metaModel.getCompedRelationCode();
    long sysTime = AdapterExtractorContext.getInstance().getGlobalTime();

    for (int i = 0, size = metadatas.size(); i < size; i++) {

        AbstractMetadata metadata = metadatas.get(i);
        if (metadata.isHasExist()) {
            // ??,???
            continue;
        }/*from   w w  w  . j  ava  2  s  . c  o  m*/

        // ?ID
        ps.setString(1, metadata.getParentMetadata().getId());
        // ?ID
        ps.setString(2, parentMetaModelId);
        // ?ID
        ps.setString(3, metadata.getId());
        // ?ID
        ps.setString(4, metaModelId);
        // ???
        ps.setString(5, relationshipName);
        // 
        ps.setLong(6, sysTime);

        setPs(ps, 6);

        ps.addBatch();
        ps.clearParameters();

        if (++super.count % super.batchSize == 0) {
            ps.executeBatch();
            ps.clearBatch();
        }
    }

}

From source file:org.openbel.framework.core.kam.JdbcKAMLoaderImpl.java

/**
 * {@inheritDoc}//from  ww  w .  j  a  v  a  2  s  .c  om
 */
@Override
public void loadStatementAnnotationMap(StatementAnnotationMapTable samt) throws SQLException {
    Map<Integer, Set<AnnotationPair>> sidAnnotationIndex = samt.getStatementAnnotationPairsIndex();

    PreparedStatement saps = getPreparedStatement(STATEMENT_ANNOTATION_SQL);

    final Set<Entry<Integer, Set<AnnotationPair>>> entries = sidAnnotationIndex.entrySet();
    for (final Entry<Integer, Set<AnnotationPair>> entry : entries) {
        final Integer sid = entry.getKey();
        for (final AnnotationPair annotation : entry.getValue()) {
            // XXX offset
            saps.setInt(1, sid + 1);
            // XXX offset
            saps.setInt(2, annotation.getAnnotationValueId() + 1);
            saps.addBatch();
        }
    }
    saps.executeBatch();
}

From source file:com.pactera.edg.am.metamanager.extractor.dao.helper.DeleteMetadataAlterHelper.java

protected void doInPreparedStatement(PreparedStatement ps, String metaModelCode, boolean hasChildMetaModel,
        List<AbstractMetadata> metadatas) throws SQLException {
    try {/*from  ww  w .  j  a  v  a  2s.c  o m*/
        for (AbstractMetadata metadata : metadatas) {
            // ?ID
            String sequenceId = sequenceDao.getUuid();
            ps.setString(1, sequenceId);
            // ?,1
            ps.setString(2, "1");
            // ID
            ps.setString(3, taskInstanceId);
            // // ?ID
            // ps.setString(4, metadata.getId());
            // // 
            // ps.setString(5, metaModelCode);
            // ID
            ps.setString(4, userId);

            // START_TIME?START_TIME
            ps.setLong(5, metadata.getStartTime());
            // : ALTERATION_TIME
            ps.setLong(6, startTime);

            // OLD_START_TIME ???OLD_START_TIME??
            ps.setNull(7, java.sql.Types.BIGINT);
            // ?ID
            ps.setString(8, metadata.getId());

            ps.addBatch();
            ps.clearParameters();

            if (++super.count % super.batchSize == 0) {
                ps.executeBatch();
                ps.clearBatch();
            }

        }
    } catch (SQLException e) {
        // ??,????,,??
        log.warn("??!", e);
    }

}