Example usage for java.sql PreparedStatement executeBatch

List of usage examples for java.sql PreparedStatement executeBatch

Introduction

In this page you can find the example usage for java.sql PreparedStatement 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:org.jasig.ssp.util.importer.job.staging.SqlServerStagingTableWriter.java

@Override
public void write(final List<? extends RawItem> items) {

    NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    String fileName = items.get(0).getResource().getFilename();
    final String[] tableName = fileName.split("\\.");

    Integer batchStart = (Integer) (stepExecution.getExecutionContext().get("batchStart") == null ? null
            : stepExecution.getExecutionContext().get("batchStart"));
    Integer batchStop = (Integer) (stepExecution.getExecutionContext().get("batchStop") == null ? null
            : stepExecution.getExecutionContext().get("batchStop"));
    Object currentEntity = stepExecution.getExecutionContext().get("currentEntity");

    if (currentEntity == null || !currentEntity.equals(tableName[0])) {
        batchStart = 0;//from   ww w.j a  v a 2 s .  c om
        batchStop = items.size() - 1;
        currentEntity = tableName[0];
        stepExecution.getExecutionContext().put("currentEntity", currentEntity);
        stepExecution.getExecutionContext().put("batchStart", batchStart);
        stepExecution.getExecutionContext().put("batchStop", batchStop);
    } else {
        batchStart = batchStop + 1;
        batchStop = (Integer) batchStart + items.size() - 1;
        stepExecution.getExecutionContext().put("batchStart", batchStart);
        stepExecution.getExecutionContext().put("batchStop", batchStop);
    }

    RawItem firstItem = items.get(0);
    Resource firstItemResource = firstItem.getResource();

    if (currentResource == null || !(this.currentResource.equals(firstItemResource))) {
        this.orderedHeaders = writeHeader(firstItem);
        this.currentResource = firstItemResource;
    }

    StringBuilder insertSql = new StringBuilder();
    insertSql.append("INSERT INTO stg_" + tableName[0] + " (batch_id,");
    StringBuilder valuesSqlBuilder = new StringBuilder();
    valuesSqlBuilder.append(" VALUES (?,");
    for (String header : this.orderedHeaders) {
        insertSql.append(header).append(",");
        valuesSqlBuilder.append("?").append(",");
    }
    insertSql.setLength(insertSql.length() - 1); // trim comma
    valuesSqlBuilder.setLength(valuesSqlBuilder.length() - 1); // trim comma
    insertSql.append(")");
    valuesSqlBuilder.append(");");
    insertSql.append(valuesSqlBuilder);

    final AtomicInteger batchStartRef = new AtomicInteger(batchStart);
    final String sql = insertSql.toString();
    jdbcTemplate.getJdbcOperations().execute(sql, new PreparedStatementCallback() {
        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            for (RawItem item : items) {
                final List<Object> paramsForLog = new ArrayList(orderedHeaders.length);
                int counter = 1;
                paramsForLog.add(batchStartRef.get());
                StatementCreatorUtils.setParameterValue(ps, counter, SqlTypeValue.TYPE_UNKNOWN,
                        batchStartRef.getAndIncrement());
                counter++;
                for (String header : orderedHeaders) {
                    final Map<String, String> record = item.getRecord();
                    String value = record.get(header);
                    final Integer sqlType = metadataRepository.getRepository().getColumnMetadataRepository()
                            .getColumnMetadata(new ColumnReference(tableName[0], header)).getJavaSqlType();
                    paramsForLog.add(value);
                    StatementCreatorUtils.setParameterValue(ps, counter, sqlType, value);
                    counter++;
                }
                sayQuery(sql, paramsForLog);
                ps.addBatch();
            }
            return ps.executeBatch();
        }
    });
    batchStart = batchStartRef.get();
    say("******CHUNK SQLSERVER******");
}

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   www. jav  a2 s  . co  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.jasig.ssp.util.importer.job.staging.PostgresStagingTableWriter.java

@Override
public void write(final List<? extends RawItem> items) {

    NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    String fileName = items.get(0).getResource().getFilename();
    final String[] tableName = fileName.split("\\.");

    Integer batchStart = (Integer) (stepExecution.getExecutionContext().get("batchStart") == null ? null
            : stepExecution.getExecutionContext().get("batchStart"));
    Integer batchStop = (Integer) (stepExecution.getExecutionContext().get("batchStop") == null ? null
            : stepExecution.getExecutionContext().get("batchStop"));
    Object currentEntity = stepExecution.getExecutionContext().get("currentEntity");

    if (currentEntity == null || !currentEntity.equals(tableName[0])) {
        batchStart = 0;/*from   ww w. j  a  v a2  s  . c  om*/
        batchStop = items.size() - 1;
        currentEntity = tableName[0];
        stepExecution.getExecutionContext().put("currentEntity", currentEntity);
        stepExecution.getExecutionContext().put("batchStart", batchStart);
        stepExecution.getExecutionContext().put("batchStop", batchStop);
    } else {
        batchStart = batchStop + 1;
        batchStop = (Integer) batchStart + items.size() - 1;
        stepExecution.getExecutionContext().put("batchStart", batchStart);
        stepExecution.getExecutionContext().put("batchStop", batchStop);
    }

    RawItem firstItem = items.get(0);
    Resource firstItemResource = firstItem.getResource();

    if (currentResource == null || !(this.currentResource.equals(firstItemResource))) {
        this.orderedHeaders = writeHeader(firstItem);
        this.currentResource = firstItemResource;
    }

    StringBuilder insertSql = new StringBuilder();
    insertSql.append("INSERT INTO stg_" + tableName[0] + " (batch_id,");
    StringBuilder valuesSqlBuilder = new StringBuilder();
    valuesSqlBuilder.append(" VALUES (?,");
    for (String header : this.orderedHeaders) {
        insertSql.append(header).append(",");
        valuesSqlBuilder.append("?").append(",");
    }
    insertSql.setLength(insertSql.length() - 1); // trim comma
    valuesSqlBuilder.setLength(valuesSqlBuilder.length() - 1); // trim comma
    insertSql.append(")");
    valuesSqlBuilder.append(");");
    insertSql.append(valuesSqlBuilder);

    final AtomicInteger batchStartRef = new AtomicInteger(batchStart);
    final String sql = insertSql.toString();

    jdbcTemplate.getJdbcOperations().execute(sql, new PreparedStatementCallback() {
        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            for (RawItem item : items) {
                final List<Object> paramsForLog = new ArrayList(orderedHeaders.length);
                int counter = 1;
                paramsForLog.add(batchStartRef.get());
                StatementCreatorUtils.setParameterValue(ps, counter, SqlTypeValue.TYPE_UNKNOWN,
                        batchStartRef.getAndIncrement());
                counter++;
                for (String header : orderedHeaders) {
                    final Map<String, String> record = item.getRecord();
                    String value = record.get(header);
                    final Integer sqlType = metadataRepository.getRepository().getColumnMetadataRepository()
                            .getColumnMetadata(new ColumnReference(tableName[0], header)).getJavaSqlType();
                    paramsForLog.add(value);
                    StatementCreatorUtils.setParameterValue(ps, counter, sqlType, value);
                    counter++;
                }
                sayQuery(sql, paramsForLog);
                ps.addBatch();
            }
            return ps.executeBatch();
        }
    });

    batchStart = batchStartRef.get();

    say("******CHUNK POSTGRES******");
}

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

/**
 * {@inheritDoc}//from  w  w w  .jav  a  2  s.  c o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void addItemData(long briefcaseId, List<BriefcaseItemData> itemDatas) throws FxApplicationException {
    if (itemDatas == null || itemDatas.size() == 0)
        return;
    Briefcase br = load(briefcaseId); // check read permissions
    Connection con = null;
    PreparedStatement stmt = null;
    long lastId = -1;
    int pos = -1;
    try {
        con = Database.getDbConnection();

        for (BriefcaseItemData itemData : itemDatas) {
            if (lastId != itemData.getId()) {
                lastId = itemData.getId();
                if (stmt != null) {
                    stmt.executeBatch();
                    stmt.close();
                }
                //existance check and evaluate position
                stmt = con.prepareStatement(
                        "SELECT COUNT(*) FROM " + TBL_BRIEFCASE_DATA + " WHERE briefcase_id=? AND id=?");
                stmt.setLong(1, briefcaseId);
                stmt.setLong(2, itemData.getId());
                ResultSet rs = stmt.executeQuery();
                if (rs == null || !rs.next() || rs.getLong(1) != 1)
                    throw new FxNotFoundException(LOG, "ex.briefcase.notFound.item", itemData.getId(),
                            br.getName());
                stmt.close();
                stmt = con.prepareStatement(
                        "SELECT MAX(pos) FROM " + TBL_BRIEFCASE_DATA_ITEM + " WHERE briefcase_id=? AND id=?");
                stmt.setLong(1, briefcaseId);
                stmt.setLong(2, itemData.getId());
                rs = stmt.executeQuery();
                pos = rs.next() ? rs.getInt(1) : 0;
                stmt.close();
                stmt = con.prepareStatement("INSERT INTO " + TBL_BRIEFCASE_DATA_ITEM
                        + "(briefcase_id, id, pos, intflag1, intflag2, intflag3, longflag1, longflag2, metadata) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                stmt.setLong(1, briefcaseId);
                stmt.setLong(2, itemData.getId());
            }
            if (stmt == null) {
                LOG.fatal("PreparedStatement was null trying to add briefcase item data!");
                continue;
            }
            stmt.setLong(3, ++pos);
            if (itemData.isIntFlagSet(1))
                stmt.setInt(4, itemData.getIntFlag1());
            else
                stmt.setNull(4, Types.INTEGER);
            if (itemData.isIntFlagSet(2))
                stmt.setInt(5, itemData.getIntFlag2());
            else
                stmt.setNull(5, Types.INTEGER);
            if (itemData.isIntFlagSet(3))
                stmt.setInt(6, itemData.getIntFlag3());
            else
                stmt.setNull(6, Types.INTEGER);
            if (itemData.isLongFlagSet(1))
                stmt.setLong(7, itemData.getLongFlag1());
            else
                stmt.setNull(7, Types.BIGINT);
            if (itemData.isLongFlagSet(2))
                stmt.setLong(8, itemData.getLongFlag2());
            else
                stmt.setNull(8, Types.BIGINT);
            stmt.setString(9, itemData.getMetaData());
            stmt.addBatch();
        }
        if (stmt != null)
            stmt.executeBatch();
    } catch (Exception e) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, e, "ex.briefcase.addItemData", br.getName(), lastId, e.getMessage());
    } finally {
        Database.closeObjects(BriefcaseEngineBean.class, con, stmt);
    }
}

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 w ww. j a v  a 2  s.com
        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);
    }

}

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

private void updateAuthzUserName() throws SQLException {
    log.info("Updating Authz UserName for API Manager started");
    Connection connection = null;
    PreparedStatement selectStatement = null;
    ResultSet resultSet = null;//from  w w  w  . j a  v a2s .  c o  m

    ArrayList<AccessTokenInfo> updateValues = new ArrayList<>();
    try {
        String selectQuery = "SELECT DISTINCT AUTHZ_USER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE AUTHZ_USER LIKE '%@%'";

        connection = APIMgtDBUtil.getConnection();
        selectStatement = connection.prepareStatement(selectQuery);
        resultSet = selectStatement.executeQuery();

        while (resultSet.next()) {
            String authzUser = resultSet.getString("AUTHZ_USER");
            String usernameWithoutDomain = MultitenantUtils.getTenantAwareUsername(authzUser);

            AccessTokenInfo accessTokenInfo = new AccessTokenInfo(usernameWithoutDomain, authzUser);
            updateValues.add(accessTokenInfo);
        }
    } finally {
        APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
    }

    if (!updateValues.isEmpty()) { // If user names that need to be updated exist
        PreparedStatement updateStatement = null;

        try {
            connection = APIMgtDBUtil.getConnection();
            connection.setAutoCommit(false);

            updateStatement = connection.prepareStatement(
                    "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET AUTHZ_USER = ?" + " WHERE AUTHZ_USER = ?");

            for (AccessTokenInfo accessTokenInfo : updateValues) {
                updateStatement.setString(1, accessTokenInfo.usernameWithoutDomain);
                updateStatement.setString(2, accessTokenInfo.authzUser);
                updateStatement.addBatch();
            }
            updateStatement.executeBatch();

            connection.commit();
        } finally {
            APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
        }
    }
    log.info("Updating Authz UserName for API Manager completed");
}

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

@Override
public void moveCommandOperations() throws ArchivalDAOException {
    Statement stmt = null;//w  w  w. jav a 2  s . com
    PreparedStatement stmt2 = null;
    Statement stmt3 = null;
    ResultSet rs = null;
    try {
        Connection conn = ArchivalSourceDAOFactory.getConnection();
        String sql = "SELECT * FROM DM_COMMAND_OPERATION WHERE OPERATION_ID IN "
                + "(SELECT ID FROM DM_ARCHIVED_OPERATIONS)";
        stmt = this.createMemoryEfficientStatement(conn);
        rs = stmt.executeQuery(sql);

        Connection conn2 = ArchivalDestinationDAOFactory.getConnection();

        sql = "INSERT INTO DM_COMMAND_OPERATION_ARCH VALUES(?,?,?)";
        stmt2 = conn2.prepareStatement(sql);

        int count = 0;
        while (rs.next()) {
            stmt2.setInt(1, rs.getInt("OPERATION_ID"));
            stmt2.setInt(2, rs.getInt("ENABLED"));
            stmt2.setTimestamp(3, this.currentTimestamp);
            stmt2.addBatch();

            if (++count % batchSize == 0) {
                stmt2.executeBatch();
            }
        }
        stmt2.executeBatch();
        if (log.isDebugEnabled()) {
            log.debug(count + " [COMMAND_OPERATION] Records copied to the archival table. Starting deletion");
        }
        sql = "DELETE FROM DM_COMMAND_OPERATION"
                + "  WHERE OPERATION_ID IN (SELECT ID FROM DM_ARCHIVED_OPERATIONS)";
        stmt3 = conn.createStatement();
        int affected = stmt3.executeUpdate(sql);
        if (log.isDebugEnabled()) {
            log.debug(affected + " Rows deleted");
        }
    } catch (SQLException e) {
        throw new ArchivalDAOException("Error occurred while moving command operations", e);
    } finally {
        ArchivalDAOUtil.cleanupResources(stmt, rs);
        ArchivalDAOUtil.cleanupResources(stmt2);
        ArchivalDAOUtil.cleanupResources(stmt3);
    }
}

From source file:org.wso2.carbon.identity.claim.metadata.mgt.dao.LocalClaimDAO.java

private void addClaimAttributeMappings(Connection connection, int localClaimId,
        List<AttributeMapping> attributeMappings, int tenantId) throws ClaimMetadataException {

    PreparedStatement prepStmt = null;
    if (localClaimId > 0 && attributeMappings != null) {
        try {//from   w  w w .  java 2 s.co  m
            String query = SQLConstants.ADD_CLAIM_MAPPED_ATTRIBUTE;
            prepStmt = connection.prepareStatement(query);
            for (AttributeMapping attributeMapping : attributeMappings) {
                if (StringUtils.isBlank(attributeMapping.getUserStoreDomain())) {
                    throw new ClaimMetadataException(
                            "User store domain of mapped Attribute cannot be empty for "
                                    + "the local claim id : " + localClaimId);
                } else if (StringUtils.isBlank(attributeMapping.getAttributeName())) {
                    throw new ClaimMetadataException(
                            "Mapped attribute of the local claim id : " + localClaimId + " cannot be empty");
                }
                prepStmt.setInt(1, localClaimId);
                prepStmt.setString(2, attributeMapping.getUserStoreDomain());
                prepStmt.setString(3, attributeMapping.getAttributeName());
                prepStmt.setInt(4, tenantId);
                prepStmt.addBatch();
            }

            prepStmt.executeBatch();
        } catch (SQLException e) {
            throw new ClaimMetadataException("Error while adding attribute mappings", e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
        }
    }
}

From source file:org.sakaiproject.nakamura.lite.storage.jdbc.WideColumnIndexer.java

public void index(Map<String, PreparedStatement> statementCache, String keySpace, String columnFamily,
        String key, String rid, Map<String, Object> values) throws StorageClientException, SQLException {
    ResultSet rs = null;//from   w ww . j  av a  2 s . c  o m

    try {
        Set<String> removeArrayColumns = Sets.newHashSet();
        Set<String> removeColumns = Sets.newHashSet();
        Map<String, Object[]> updateArrayColumns = Maps.newHashMap();
        Map<String, Object> updateColumns = Maps.newHashMap();
        for (Entry<String, Object> e : values.entrySet()) {
            String k = e.getKey();
            Object o = e.getValue();
            Object[] valueMembers = (o instanceof Object[]) ? (Object[]) o : new Object[] { o };
            if (shouldIndex(keySpace, columnFamily, k)) {
                if (isColumnArray(keySpace, columnFamily, k)) {
                    if (o instanceof RemoveProperty || o == null || valueMembers.length == 0) {
                        removeArrayColumns.add(k);
                    } else {
                        removeArrayColumns.add(k);
                        updateArrayColumns.put(k, valueMembers);
                    }
                } else {
                    if (o instanceof RemoveProperty || o == null || valueMembers.length == 0) {
                        removeColumns.add(k);
                    } else {
                        updateColumns.put(k, valueMembers[0]);
                    }

                }
            }
        }

        if (!StorageClientUtils.isRoot(key)
                && getColumnName(keySpace, columnFamily, InternalContent.PARENT_HASH_FIELD) != null) {
            String parent = StorageClientUtils.getParentObjectPath(key);
            String hash = client.rowHash(keySpace, columnFamily, parent);
            LOGGER.debug("Hash of {}:{}:{} is {} ", new Object[] { keySpace, columnFamily, parent, hash });
            updateColumns.put(InternalContent.PARENT_HASH_FIELD, hash);
        }

        LOGGER.debug("Removing Array {} ", removeArrayColumns);
        LOGGER.debug("Updating Array {} ", updateArrayColumns);
        LOGGER.debug("Removing  {} ", removeColumns);
        LOGGER.debug("Updating  {} ", updateColumns);

        // arrays are stored in css, so we can re-use css sql.
        PreparedStatement removeStringColumn = client.getStatement(keySpace, columnFamily,
                JDBCStorageClient.SQL_REMOVE_STRING_COLUMN, rid, statementCache);
        int nbatch = 0;
        for (String column : removeArrayColumns) {
            removeStringColumn.clearWarnings();
            removeStringColumn.clearParameters();
            removeStringColumn.setString(1, rid);
            removeStringColumn.setString(2, column);
            removeStringColumn.addBatch();
            LOGGER.debug("Removing {} {} ", rid, column);
            nbatch++;
        }
        if (nbatch > 0) {
            long t = System.currentTimeMillis();
            removeStringColumn.executeBatch();
            checkSlow(t, client.getSql(keySpace, columnFamily, JDBCStorageClient.SQL_REMOVE_STRING_COLUMN));
            nbatch = 0;
        }

        // add the column values in
        PreparedStatement insertStringColumn = client.getStatement(keySpace, columnFamily,
                JDBCStorageClient.SQL_INSERT_STRING_COLUMN, rid, statementCache);
        for (Entry<String, Object[]> e : updateArrayColumns.entrySet()) {
            for (Object o : e.getValue()) {
                insertStringColumn.clearWarnings();
                insertStringColumn.clearParameters();
                insertStringColumn.setString(1, o.toString());
                insertStringColumn.setString(2, rid);
                insertStringColumn.setString(3, e.getKey());
                insertStringColumn.addBatch();
                LOGGER.debug("Inserting {} {} {} ", new Object[] { o.toString(), rid, e.getKey() });
                nbatch++;
            }
        }
        if (nbatch > 0) {
            long t = System.currentTimeMillis();
            insertStringColumn.executeBatch();
            checkSlow(t, client.getSql(keySpace, columnFamily, JDBCStorageClient.SQL_INSERT_STRING_COLUMN));
            nbatch = 0;
        }
        if (removeColumns.size() == 0 && updateColumns.size() == 0) {
            return; // nothing to add or remove, do nothing.
        }

        if (removeColumns.size() > 0 && updateColumns.size() == 0) {
            // exists, columns to remove, none to update, therefore
            // delete row this assumes that the starting point is a
            // complete map
            PreparedStatement deleteWideStringColumn = client.getStatement(keySpace, columnFamily,
                    SQL_DELETE_WIDESTRING_ROW, rid, statementCache);
            deleteWideStringColumn.clearParameters();
            deleteWideStringColumn.setString(1, rid);
            long t = System.currentTimeMillis();
            deleteWideStringColumn.execute();
            checkSlow(t, client.getSql(keySpace, columnFamily, SQL_DELETE_WIDESTRING_ROW));
            LOGGER.debug("Executed {} with {} ", deleteWideStringColumn, rid);
        } else if (updateColumns.size() > 0 || removeColumns.size() > 0) {
            //
            // build an update query, record does not exists, but there
            // is stuff to add
            String[] sqlParts = StringUtils
                    .split(client.getSql(keySpace, columnFamily, SQL_UPDATE_WIDESTRING_ROW), ";");
            StringBuilder setOperations = new StringBuilder();
            for (Entry<String, Object> e : updateColumns.entrySet()) {
                join(setOperations, " ,").append(
                        MessageFormat.format(sqlParts[1], getColumnName(keySpace, columnFamily, e.getKey())));
            }
            for (String toRemove : removeColumns) {
                join(setOperations, " ,").append(
                        MessageFormat.format(sqlParts[1], getColumnName(keySpace, columnFamily, toRemove)));
            }
            String finalSql = MessageFormat.format(sqlParts[0], setOperations);
            LOGGER.debug("Performing {} ", finalSql);
            PreparedStatement updateColumnPst = client.getStatement(finalSql, statementCache);
            updateColumnPst.clearWarnings();
            updateColumnPst.clearParameters();
            int i = 1;
            for (Entry<String, Object> e : updateColumns.entrySet()) {
                updateColumnPst.setString(i, e.getValue().toString());
                LOGGER.debug("   Param {} {} ", i, e.getValue().toString());
                i++;
            }
            for (String toRemove : removeColumns) {
                updateColumnPst.setNull(i, toSqlType(columnFamily, toRemove));
                LOGGER.debug("   Param {} NULL ", i);
                i++;
            }
            updateColumnPst.setString(i, rid);
            long t = System.currentTimeMillis();
            int n = updateColumnPst.executeUpdate();
            checkSlow(t, finalSql);
            if (n == 0) {
                // part 0 is the final ,part 1 is the template for column names,
                // part 2 is the template for parameters.
                // insert into x ( columnsnames ) values ()
                StringBuilder columnNames = new StringBuilder();
                StringBuilder paramHolders = new StringBuilder();
                for (Entry<String, Object> e : updateColumns.entrySet()) {
                    columnNames.append(" ,").append(getColumnName(keySpace, columnFamily, e.getKey()));
                    paramHolders.append(" ,").append("?");
                }
                finalSql = MessageFormat.format(
                        client.getSql(keySpace, columnFamily, SQL_INSERT_WIDESTRING_ROW),
                        columnNames.toString(), paramHolders.toString());
                LOGGER.debug("Insert SQL {} ", finalSql);
                PreparedStatement insertColumnPst = client.getStatement(finalSql, statementCache);
                insertColumnPst.clearWarnings();
                insertColumnPst.clearParameters();
                insertColumnPst.setString(1, rid);
                i = 2;
                for (Entry<String, Object> e : updateColumns.entrySet()) {
                    LOGGER.debug("   Param {} {} ", i, e.getValue().toString());
                    insertColumnPst.setString(i, e.getValue().toString());
                    i++;
                }
                t = System.currentTimeMillis();
                insertColumnPst.executeUpdate();
                checkSlow(t, finalSql);
            }
        }
    } finally {
        if (rs != null) {
            rs.close();
        }
    }

}

From source file:com.archivas.clienttools.arcutils.utils.database.ManagedJobSchema.java

private void insertIntoTempTable(PooledDbConnection conn, Set<String> paths) throws SQLException {
    PreparedStatement insertStmt = conn.prepareStatement(INSERT_INTO_TEMP_TABLE_STMT_NAME,
            insertIntoTempTableSql);//ww  w . j a v  a  2 s . co m

    for (String path : paths) {
        insertStmt.clearParameters();
        insertStmt.setString(1, path);
        insertStmt.addBatch();
    }

    insertStmt.executeBatch();
    conn.commit();
}