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.openbel.framework.core.kam.JdbcKAMLoaderImpl.java

/**
 * {@inheritDoc}/*from ww w  .  ja  va 2 s  . co  m*/
 */
@Override
public void loadRelationshipTypes() throws SQLException {
    PreparedStatement ps = getPreparedStatement(RELATIONSHIP_TYPE_SQL);
    for (RelationshipType r : RelationshipType.values()) {
        String relationshipName = r.getDisplayValue();
        ps.setInt(1, r.getValue());
        ps.setString(2, relationshipName);
        ps.addBatch();
    }

    ps.executeBatch();
}

From source file:com.yahoo.ycsb.db.PostgreSQLJsonbClient.java

@Override
public Status insert(String tableName, String key, HashMap<String, ByteIterator> values) {
    try {/* www  .ja  v a  2s.c o m*/
        StatementType type = new StatementType(StatementType.Type.INSERT, tableName, 1, "fields",
                getShardIndexByKey(key));
        PreparedStatement insertStatement = cachedStatements.get(type);
        if (insertStatement == null) {
            insertStatement = createAndCacheInsertStatement(type, key);
        }
        String value = getJsonString(values);
        insertStatement.setString(1, key);
        insertStatement.setString(2, value);
        int result;
        if (batchSize > 0) {
            insertStatement.addBatch();
            if (++numRowsInBatch % batchSize == 0) {
                int[] results = insertStatement.executeBatch();
                for (int r : results) {
                    if (r != 1) {
                        return Status.ERROR;
                    }
                }
                return Status.OK;
            }
            return Status.BATCHED_OK;
        } else {
            result = insertStatement.executeUpdate();
        }
        if (result == 1) {
            return Status.OK;
        }
        return Status.UNEXPECTED_STATE;
    } catch (SQLException e) {
        System.err.println("Error in processing insert to table: " + tableName + e);
        return Status.ERROR;
    }
}

From source file:com.sec.ose.osi.localdb.identification.IdentificationDBManager.java

synchronized public static void executeUpdateStatement(PreparedStatement tmpStatement) {

    if (tmpStatement == null) {
        return;// w  w w. j  a  va2  s  . co m
    }

    try {
        tmpStatement.executeBatch();
        tmpStatement.clearBatch();
    } catch (SQLException e) {
        log.warn(e);
    }
}

From source file:org.obm.push.backend.obm22.mail.EmailCacheStorage.java

private void updateDbCache(BackendSession bs, Integer devId, Integer collectionId, final Set<Long> data)
        throws SQLException {
    Set<Long> toRemove = new HashSet<Long>();
    Set<Long> oldUids = loadMailFromDb(bs, devId, collectionId);
    if (oldUids != null) {
        toRemove.addAll(oldUids);/*from   w ww . ja  va  2 s .co m*/
        toRemove.removeAll(data);
    }

    Set<Long> toInsert = new HashSet<Long>();
    toInsert.addAll(data);
    if (oldUids != null) {
        toInsert.removeAll(oldUids);
    }

    if (toRemove.size() == 0 && toInsert.size() == 0) {
        return;
    }

    PreparedStatement del = null;
    PreparedStatement insert = null;

    if (logger.isDebugEnabled()) {
        logger.debug(debugName + " should run a batch with " + toRemove.size() + " deletions & "
                + toInsert.size() + " insertions.");
    }
    Connection con = null;
    UserTransaction ut = getUserTransaction();
    try {
        ut.begin();
        con = OBMPoolActivator.getDefault().getConnection();
        del = con.prepareStatement(
                "DELETE FROM opush_sync_mail WHERE collection_id=? AND device_id=? AND mail_uid=?");
        for (Long l : toRemove) {
            del.setInt(1, collectionId);
            del.setInt(2, devId);
            del.setInt(3, l.intValue());
            del.addBatch();
        }
        del.executeBatch();

        insert = con.prepareStatement(
                "INSERT INTO opush_sync_mail (collection_id, device_id, mail_uid) VALUES (?, ?, ?)");
        for (Long l : toInsert) {
            insert.setInt(1, collectionId);
            insert.setInt(2, devId);
            insert.setInt(3, l.intValue());
            insert.addBatch();
        }
        insert.executeBatch();
        ut.commit();
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        JDBCUtils.rollback(con);
    } finally {
        JDBCUtils.cleanup(null, del, null);
        JDBCUtils.cleanup(con, insert, null);
    }
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

@Override
public void massDeletePredecessors(List<TaskPredecessor> predecessors, @CacheKey Integer sAccountId) {
    Lock lock = DistributionLockUtil.getLock("gantt-predecessor-service" + sAccountId);
    try {// w  w w  .ja  va 2  s  .  c o m
        if (lock.tryLock(30, TimeUnit.SECONDS)) {
            try (Connection connection = dataSource.getConnection()) {
                connection.setAutoCommit(false);
                PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM "
                        + "`m_prj_predecessor` WHERE sourceType=? AND predestype=? AND sourceId=? AND descId=? AND descType=?");
                for (int i = 0; i < predecessors.size(); i++) {
                    preparedStatement.setString(1, predecessors.get(i).getSourcetype());
                    preparedStatement.setString(2, predecessors.get(i).getPredestype());
                    preparedStatement.setInt(3, predecessors.get(i).getSourceid());
                    preparedStatement.setInt(4, predecessors.get(i).getDescid());
                    preparedStatement.setString(5, predecessors.get(i).getDesctype());
                    preparedStatement.addBatch();
                }
                preparedStatement.executeBatch();
                connection.commit();
            }
        }
    } catch (Exception e) {
        throw new MyCollabException(e);
    } finally {
        DistributionLockUtil.removeLock("gantt-predecessor-service" + sAccountId);
        lock.unlock();
    }
}

From source file:com.nabla.wapp.server.auth.UserManager.java

public boolean updateUserDefinition(final Integer objectId, final Integer userId, final SelectionDelta delta)
        throws SQLException {
    Assert.argumentNotNull(userId);/*from w w  w  .  j a v  a  2  s  . c  o  m*/
    Assert.argumentNotNull(delta);

    final LockTableGuard lock = new LockTableGuard(conn, LOCK_USER_TABLES);
    try {
        final ConnectionTransactionGuard guard = new ConnectionTransactionGuard(conn);
        try {
            if (delta.isRemovals()) {
                if (objectId == null)
                    Database.executeUpdate(conn,
                            "DELETE FROM user_definition WHERE object_id IS NULL AND user_id=? AND role_id IN (?);",
                            userId, delta.getRemovals());
                else
                    Database.executeUpdate(conn,
                            "DELETE FROM user_definition WHERE object_id=? AND user_id=? AND role_id IN (?);",
                            objectId, userId, delta.getRemovals());
            }
            if (delta.isAdditions()) {
                final PreparedStatement stmt = conn.prepareStatement(
                        "INSERT INTO user_definition (object_id, user_id, role_id) VALUES(?,?,?);");
                try {
                    stmt.clearBatch();
                    if (objectId == null)
                        stmt.setNull(1, Types.BIGINT);
                    else
                        stmt.setInt(1, objectId);
                    stmt.setInt(2, userId);
                    for (final Integer childId : delta.getAdditions()) {
                        stmt.setInt(3, childId);
                        stmt.addBatch();
                    }
                    if (!Database.isBatchCompleted(stmt.executeBatch()))
                        return false;
                } finally {
                    stmt.close();
                }
            }
            return guard.setSuccess(updateUserRoleTable());
        } finally {
            guard.close();
        }
    } finally {
        lock.close();
    }
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.feature.AbstractFeatureDAO.java

@Override
public List<ProfileFeature> updateProfileFeatures(List<ProfileFeature> features, int profileId)
        throws FeatureManagerDAOException {

    Connection conn;//  w ww  . j a  v a  2  s .  c  o m
    PreparedStatement stmt = null;
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    try {
        conn = this.getConnection();
        String query = "UPDATE DM_PROFILE_FEATURES SET CONTENT = ? WHERE PROFILE_ID = ? AND FEATURE_CODE = ? AND"
                + " TENANT_ID = ?";

        stmt = conn.prepareStatement(query);
        for (ProfileFeature feature : features) {
            stmt.setBytes(1, PolicyManagerUtil.getBytes(feature.getContent()));
            stmt.setInt(2, profileId);
            stmt.setString(3, feature.getFeatureCode());
            stmt.setInt(4, tenantId);
            stmt.addBatch();
            //Not adding the logic to check the size of the stmt and execute if the size records added is over 1000
        }
        stmt.executeBatch();

    } catch (SQLException | IOException e) {
        throw new FeatureManagerDAOException("Error occurred while adding the feature list to the database.",
                e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, null);
    }
    return features;
}

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

/**
 * Insert text into PostgreSQL//from w ww .  ja  va 2s  .  c  o m
 * 
 * @param files 
 *           List of Strings of text to insert
 * 
 * @return number of rows affected
 * 
 * @throws Exception TODO describe exception
 */
public int addFile(String action_number, String make, String model, String year, String compname,
        String mfr_name, String odate, String cdate, String campno, String subject, String summary)
        throws Exception {

    String sql = "INSERT INTO reportedErrors (action_number, make, model, year, compname, mfr_name, odate, cdate, campno, subject, summary) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,)";
    Connection connection = null;
    PreparedStatement statement = null;

    try {
        connection = getConnection();
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(sql);

        statement.setString(1, action_number);
        statement.setString(2, make);
        statement.setString(3, model);
        statement.setString(4, year);
        statement.setString(5, compname);
        statement.setString(6, mfr_name);
        statement.setString(7, odate);
        statement.setString(8, cdate);
        statement.setString(9, campno);
        statement.setString(10, subject);
        statement.setString(11, summary);

        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:org.owasp.dependencycheck.data.nvdcve.CveDB.java

/**
 * Executes batch inserts of vulnerabilities when property
 * database.batchinsert.maxsize is reached.
 *
 * @param pVulnerability the vulnerability
 * @param pVulnerableSoftware the vulnerable software
 * @param pInsertSoftware the prepared statement to batch execute
 * @throws SQLException thrown when the batch cannot be executed
 *//*from   w ww .j a  v a  2 s.co  m*/
private void executeBatch(Vulnerability pVulnerability, VulnerableSoftware pVulnerableSoftware,
        PreparedStatement pInsertSoftware) throws SQLException {
    try {
        pInsertSoftware.executeBatch();
    } catch (SQLException ex) {
        if (ex.getMessage().contains("Duplicate entry")) {
            final String msg = String.format("Duplicate software key identified in '%s:%s'",
                    pVulnerability.getName(), pVulnerableSoftware.getName());
            LOGGER.info(msg, ex);
        } else {
            throw ex;
        }
    }
}

From source file:org.wso2.carbon.identity.openidconnect.dao.RequestObjectDAOImpl.java

private void insertRequestObjectClaimValues(Map<Integer, List<String>> claimValues, Connection connection)
        throws IdentityOAuth2Exception {

    String sqlStmt = SQLQueries.STORE_IDN_OIDC_REQ_OBJECT_CLAIM_VALUES;
    PreparedStatement prepStmt = null;
    try {/*from  w ww  . ja v  a2s . c om*/
        prepStmt = connection.prepareStatement(sqlStmt);

        for (Map.Entry<Integer, List<String>> entry : claimValues.entrySet()) {
            List<String> claimValuesList = entry.getValue();
            if (CollectionUtils.isNotEmpty(claimValuesList)) {
                for (String value : claimValuesList) {
                    prepStmt.setInt(1, entry.getKey());
                    prepStmt.setString(2, value);
                    prepStmt.addBatch();
                    if (log.isDebugEnabled()) {
                        log.debug("Claim value :" + value + " is added to the batch.");
                    }
                }
            }
        }
        prepStmt.executeBatch();
        connection.commit();

    } catch (SQLException e) {
        String errorMessage = "Error when storing the request object claim values.";
        log.error(errorMessage, e);
        throw new IdentityOAuth2Exception(errorMessage, e);
    } finally {
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
    }
}