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:com.pactera.edg.am.metamanager.extractor.dao.helper.CreateMetadataHelper.java

public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
    // ?/*from w  ww. j  a  v a2s  .c  o  m*/

    Map<String, String> mAttrs = metaModel.getMAttrs();
    boolean hasChildMetaModel = metaModel.isHasChildMetaModel();

    // ???
    List<AbstractMetadata> metadatas = metaModel.getMetadatas();
    int size = metadatas.size();
    String code = "";
    String metaModelCode = "";
    MMMetadata parentMetadata = null;
    String logMsg = "";
    try {
        for (int i = 0; i < size; i++) {

            MMMetadata metadata = (MMMetadata) metadatas.get(i);
            if (metadata.isHasExist()) {
                // ??,??
                continue;
            }

            parentMetadata = metadata.getParentMetadata();
            if (parentMetadata == null) {
                String error = new StringBuilder("?:").append(metadata.getCode())
                        .append(" ,??!!").toString();
                log.error(error);
                throw new SQLException(error);
            }
            String metadataNamespace = genNamespace(parentMetadata, metadata.getId(), hasChildMetaModel);

            // ?ID
            ps.setString(1, metadata.getId());
            code = metadata.getCode();
            // ???
            ps.setString(2, code);
            // ???
            ps.setString(3,
                    (metadata.getName() == null || metadata.getName().equals("")) ? code : metadata.getName());
            // ID
            metaModelCode = metaModel.getCode();
            ps.setString(4, metaModelCode);

            // namespaceID
            ps.setString(5, metadataNamespace);
            ps.setString(6, parentMetadata.getId());
            // START_TIME: 
            ps.setLong(7, this.getGlobalTime());

            int index = setAttrs(ps, metadata, mAttrs);

            setPs(ps, metadata, index + 7);

            if (log.isDebugEnabled()) {
                log.debug(new StringBuilder().append(":parent_id:").append(parentMetadata.getId())
                        .append(",parent_code:").append(parentMetadata.getCode()).append(",instance_code:")
                        .append(code).append(",classifier_id:").append(metaModelCode).toString());
            }
            ps.addBatch();
            // ??
            ps.clearParameters();

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

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

        }
    } catch (SQLException e) {
        logMsg = new StringBuilder().append("?,?:parent_id:")
                .append(parentMetadata.getId()).append(",parent_code:").append(parentMetadata.getCode())
                .append(",instance_code:").append(code).append(",classifier_id:").append(metaModelCode)
                .append("  ?:").append(e.getLocalizedMessage()).toString();
        log.error(logMsg);
        AdapterExtractorContext.addExtractorLog(ExtractorLogLevel.ERROR, logMsg);
        throw e;
    }
    return null;
    // test for callback
    // throw new SQLException();
}

From source file:com.wabacus.system.dataimport.DataImportItem.java

private void updateDBRowData(PreparedStatement pstmt, AbsDatabaseType dbtype, List lstColsInFile,
        List<IDataType> lstColType, boolean matchFileIndex, List lstDataColValuesPerRow,
        Map<String, Object> mDataColValues) throws SQLException {
    Object objDataVal, objCol;/*  w  w  w  .j  a  va2 s . c o  m*/
    IDataType varcharTypeObj = Config.getInstance().getDataTypeByClass(VarcharType.class);
    if (this.batchupdatesize == 1)
        this.lstErrorColValuesTrace = lstDataColValuesPerRow;
    for (int i = 0; i < lstColsInFile.size(); i++) {
        objCol = lstColsInFile.get(i);
        objDataVal = null;
        if (Tools.isDefineKey("request", String.valueOf(objCol))) {
            if (request == null) {
                log.warn("??request?" + objCol
                        + "?requestnull??");
            } else {
                objDataVal = WabacusAssistant.getInstance().getValueFromRequest(request,
                        String.valueOf(objCol));
            }
        } else if (Tools.isDefineKey("session", String.valueOf(objCol))) {
            if (session == null) {
                log.warn("??session?" + objCol
                        + "?sessionnull??");
            } else {
                objDataVal = WabacusAssistant.getInstance().getValueFromSession(session,
                        String.valueOf(objCol));
            }
        } else if (matchFileIndex) {
            if ((Integer) objCol < lstDataColValuesPerRow.size())
                objDataVal = lstDataColValuesPerRow.get((Integer) objCol);
        } else {
            objDataVal = mDataColValues.get(objCol);
        }
        if (lstColType.get(i) instanceof AbsDateTimeType) {
            if (objDataVal instanceof Date) {
                ((AbsDateTimeType) lstColType.get(i)).setPreparedStatementValue(i + 1, (Date) objDataVal,
                        pstmt);
            } else {//?
                varcharTypeObj.setPreparedStatementValue(i + 1, String.valueOf(objDataVal), pstmt, dbtype);
            }
        } else {
            lstColType.get(i).setPreparedStatementValue(i + 1, (String) objDataVal, pstmt, dbtype);
        }
    }
    pstmt.addBatch();
}

From source file:org.wso2.carbon.idp.mgt.dao.IdPManagementDAO.java

/**
 * @param conn//from   w w w.  j a  v a 2 s . com
 * @param idPId
 * @param claims
 * @throws SQLException
 */
private void addIdPClaims(Connection conn, int idPId, int tenantId, Claim[] claims) throws SQLException {
    PreparedStatement prepStmt = null;

    if (claims == null || claims.length == 0) {
        return;
    }

    try {
        // SP_IDP_ID, SP_IDP_CLAIM
        String sqlStmt = IdPManagementConstants.SQLQueries.ADD_IDP_CLAIMS_SQL;
        prepStmt = conn.prepareStatement(sqlStmt);
        for (Claim claim : claims) {
            prepStmt.setInt(1, idPId);
            prepStmt.setInt(2, tenantId);
            prepStmt.setString(3, CharacterEncoder.getSafeText(claim.getClaimUri()));
            prepStmt.addBatch();
            prepStmt.clearParameters();
        }
        prepStmt.executeBatch();
    } finally {
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
    }
}

From source file:org.wso2.carbon.idp.mgt.dao.IdPManagementDAO.java

/**
 * @param conn// w w  w. j  a v a2  s  . c  o  m
 * @param idPId
 * @param idpRoleNames
 * @throws SQLException
 */
private void addIdPRoles(Connection conn, int idPId, int tenantId, String[] idpRoleNames) throws SQLException {

    PreparedStatement prepStmt = null;
    // SP_IDP_ID, SP_IDP_ROLE
    String sqlStmt = IdPManagementConstants.SQLQueries.ADD_IDP_ROLES_SQL;

    if (idpRoleNames == null || idpRoleNames.length == 0) {
        return;
    }

    try {
        prepStmt = conn.prepareStatement(sqlStmt);

        for (String idpRole : idpRoleNames) {
            prepStmt.setInt(1, idPId);
            prepStmt.setInt(2, tenantId);
            prepStmt.setString(3, CharacterEncoder.getSafeText(idpRole));
            prepStmt.addBatch();
            prepStmt.clearParameters();
        }

        prepStmt.executeBatch();

    } finally {
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
    }
}

From source file:com.oltpbenchmark.benchmarks.tpcc.TPCCLoader.java

protected int loadItem(int itemKount) {

    int k = 0;//w  ww  . j  av  a  2s . c  o m
    int t = 0;
    int randPct = 0;
    int len = 0;
    int startORIGINAL = 0;

    try {
        PreparedStatement itemPrepStmt = getInsertStatement(TPCCConstants.TABLENAME_ITEM);

        now = new java.util.Date();
        t = itemKount;
        LOG.debug("\nStart Item Load for " + t + " Items @ " + now + " ...");

        if (outputFiles == true) {
            out = new PrintWriter(new FileOutputStream(fileLocation + "item.csv"));
            LOG.debug("\nWriting Item file to: " + fileLocation + "item.csv");
        }

        Item item = new Item();

        for (int i = 1; i <= itemKount; i++) {

            item.i_id = i;
            item.i_name = TPCCUtil.randomStr(TPCCUtil.randomNumber(14, 24, gen));
            item.i_price = (float) (TPCCUtil.randomNumber(100, 10000, gen) / 100.0);

            // i_data
            randPct = TPCCUtil.randomNumber(1, 100, gen);
            len = TPCCUtil.randomNumber(26, 50, gen);
            if (randPct > 10) {
                // 90% of time i_data isa random string of length [26 .. 50]
                item.i_data = TPCCUtil.randomStr(len);
            } else {
                // 10% of time i_data has "ORIGINAL" crammed somewhere in
                // middle
                startORIGINAL = TPCCUtil.randomNumber(2, (len - 8), gen);
                item.i_data = TPCCUtil.randomStr(startORIGINAL - 1) + "ORIGINAL"
                        + TPCCUtil.randomStr(len - startORIGINAL - 9);
            }

            item.i_im_id = TPCCUtil.randomNumber(1, 10000, gen);

            k++;

            if (outputFiles == false) {
                itemPrepStmt.setLong(1, item.i_id);
                itemPrepStmt.setString(2, item.i_name);
                itemPrepStmt.setDouble(3, item.i_price);
                itemPrepStmt.setString(4, item.i_data);
                itemPrepStmt.setLong(5, item.i_im_id);
                itemPrepStmt.addBatch();

                if ((k % configCommitCount) == 0) {
                    long tmpTime = new java.util.Date().getTime();
                    String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000)
                            + "                    ";
                    LOG.debug(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
                    lastTimeMS = tmpTime;
                    itemPrepStmt.executeBatch();
                    itemPrepStmt.clearBatch();
                    transCommit();
                }
            } else {
                String str = "";
                str = str + item.i_id + ",";
                str = str + item.i_name + ",";
                str = str + item.i_price + ",";
                str = str + item.i_data + ",";
                str = str + item.i_im_id;
                out.println(str);

                if ((k % configCommitCount) == 0) {
                    long tmpTime = new java.util.Date().getTime();
                    String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000)
                            + "                    ";
                    LOG.debug(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
                    lastTimeMS = tmpTime;
                }
            }

        } // end for

        long tmpTime = new java.util.Date().getTime();
        String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000) + "                    ";
        LOG.debug(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
        lastTimeMS = tmpTime;

        if (outputFiles == false) {
            itemPrepStmt.executeBatch();
        }

        transCommit();
        now = new java.util.Date();
        LOG.debug("End Item Load @  " + now);

    } catch (SQLException se) {
        LOG.debug(se.getMessage());
        transRollback();
    } catch (Exception e) {
        e.printStackTrace();
        transRollback();
    }

    return (k);

}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

private void removeAttendees(Connection con, List<Attendee> toRemove, Event ev) throws SQLException {
    PreparedStatement ps = null;
    String q = "DELETE FROM EventLink WHERE eventlink_event_id=? AND eventlink_entity_id=? ";

    logger.info("event update will remove {} attendees.", toRemove.size());
    try {/*from  w  ww.ja va2s.  co m*/
        ps = con.prepareStatement(q);

        for (Attendee at : toRemove) {
            ps.setInt(1, ev.getObmId().getObmId());
            ps.setInt(2, at.getEntityId().getId());
            ps.addBatch();
        }

        ps.executeBatch();
    } finally {
        obmHelper.cleanup(null, ps, null);
    }
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

private void removeFromDeletedEvent(Connection con, Event ev, Collection<Integer> attendeeIds)
        throws SQLException {
    PreparedStatement deleteStatement = null;
    try {//from   ww w .j a  v a 2 s .com
        deleteStatement = con.prepareStatement(
                "DELETE FROM DeletedEvent " + "WHERE deletedevent_event_ext_id=? AND deletedevent_user_id=?");
        String extId = ev.getExtId().getExtId();
        for (int attendeeId : attendeeIds) {
            deleteStatement.setString(1, extId);
            deleteStatement.setInt(2, attendeeId);
            deleteStatement.addBatch();
        }
        deleteStatement.executeBatch();
    } finally {
        obmHelper.cleanup(null, deleteStatement, null);
    }
}

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

public void insertDiseaseStateTimeSeries(PreparedStatement pstmt, int runId, int popId, String disease_state,
        List<Double> ts) throws SQLException, ClassNotFoundException {

    logger.info("In insertDiseaseStateTimeSeries, runId={}, popId={}, disease_state={}", runId, popId,
            disease_state);//from  w  ww .  ja v a 2s  .  com
    // logger.info("Time Series is:");

    try {
        for (int i = 0; i < ts.size(); i++) {
            // logger.debug("Time Series[{}] is: {}", i, ts.get(i));
            pstmt.setInt(1, runId);
            pstmt.setInt(2, popId);
            pstmt.setInt(3, i);
            pstmt.setDouble(4, ts.get(i));
            pstmt.addBatch();
        }
    } catch (SQLException e) {
        logger.error("Error inserting disease state time series for runId={}, popId={}, disease_state={}",
                runId, popId, disease_state);

        throw new SQLException("Error inserting disease state time series for internal run id: " + runId
                + ", disease state: " + disease_state + ".   Specific error was:\n" + e.getMessage());
    }

}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

private void insertExceptions(AccessToken editor, Event ev, Connection con, EventObmId id) throws SQLException {
    PreparedStatement ps = null;
    try {/* ww w . j a v  a2s. com*/
        ps = con.prepareStatement("insert into EventException "
                + "(eventexception_parent_id, eventexception_date, eventexception_usercreate) "
                + "values (?, ?, " + editor.getObmId() + ")");
        for (Date exd : ev.getRecurrence().getExceptions()) {
            ps.setInt(1, id.getObmId());
            ps.setTimestamp(2, new Timestamp(exd.getTime()));
            ps.addBatch();
        }
        ps.executeBatch();
    } finally {
        obmHelper.cleanup(null, ps, null);
    }
}

From source file:org.wso2.appcloud.core.dao.ApplicationDAO.java

/**
 * Method for adding label, which associated with a version of an application, to database.
 *
 * @param dbConnection  database Connection
 * @param tags          list of tags//from   ww  w  .j  a  v a 2  s .  co  m
 * @param versionHashId version hash id
 * @param tenantId      tenant id
 * @throws AppCloudException
 */
public void addTags(Connection dbConnection, List<Tag> tags, String versionHashId, int tenantId)
        throws AppCloudException {

    PreparedStatement preparedStatement = null;

    try {

        preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.ADD_TAG);

        for (Tag tag : tags) {

            preparedStatement.setString(1, tag.getTagName());
            preparedStatement.setString(2, tag.getTagValue());
            preparedStatement.setString(3, versionHashId);
            preparedStatement.setString(4, tag.getDescription());
            preparedStatement.setInt(5, tenantId);

            preparedStatement.addBatch();
        }

        preparedStatement.executeBatch();

    } catch (SQLException e) {
        String msg = "Error occurred while adding tags to database for version with hash id : " + versionHashId
                + " in tenant : " + tenantId;
        throw new AppCloudException(msg, e);

    } finally {
        DBUtil.closePreparedStatement(preparedStatement);
    }
}