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

/**
 * {@inheritDoc}/* w w w.ja va 2 s  .c o  m*/
 */
@Override
public Map<String, Integer> loadObjectTypes() throws SQLException {
    int otid = 0;

    PreparedStatement ps = getPreparedStatement(OBJECT_TYPE_SQL);

    Map<String, Integer> objectTypeIdMap = new HashMap<String, Integer>();
    ps.setInt(1, otid);
    ps.setString(2, "number");
    ps.addBatch();
    objectTypeIdMap.put("number", otid);
    otid++;
    ps.setInt(1, otid);
    ps.setString(2, "varchar");
    ps.addBatch();
    objectTypeIdMap.put("varchar", otid);
    otid++;
    ps.setInt(1, otid);
    ps.setString(2, "clob");
    ps.addBatch();
    objectTypeIdMap.put("clob", otid);

    ps.executeBatch();
    return objectTypeIdMap;
}

From source file:netflow.DatabaseProxy.java

public void doAggregation() {
    //todo: the same for doAggregation(Date)
    String sql = getQuery("aggregation.insert");
    String logStr = "doAggregation(): ";
    log.info(logStr + " <<<<");
    try {/*from  ww  w  .j  ava2  s  . co m*/
        List<Integer> clients = getNetworkedClients();
        PreparedStatement pst = con.prepareStatement(sql);

        for (Integer client : clients) {
            Collection<AggregationRecord> records = askForData(client);
            for (AggregationRecord record : records) {
                pst.setInt(1, record.getClientId());
                pst.setTimestamp(2, record.getStamp());
                pst.setLong(3, record.getInput());
                pst.setLong(4, record.getOutput());
                pst.addBatch();
            }
        }

        pst.executeBatch();
        pst.close();
    } catch (SQLException e) {
        log.error(logStr + " Aggregation error: " + e.getMessage());
        e.printStackTrace(System.err);
    }
    log.info(logStr + " >>>>");
}

From source file:gov.nih.nci.caarray.dao.ArrayDaoImpl.java

/**
 * {@inheritDoc}//  w  w w .ja  va 2  s  .c  om
 */
@Override
public void createDesignElementListEntries(DesignElementList designElementList, int startIndex,
        List<Long> logicalProbeIds) {
    final Connection conn = getCurrentSession().connection();
    PreparedStatement stmt = null;
    try {
        stmt = conn.prepareStatement("insert into designelementlist_designelement "
                + "(designelementlist_id, designelement_id, designelement_index) values (?, ?, ?)");
        int i = startIndex;
        for (final Long probeId : logicalProbeIds) {
            stmt.setLong(1, designElementList.getId());
            stmt.setLong(2, probeId);
            stmt.setInt(3, i++);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (final SQLException e) {
        throw new DAOException("Error inserting elements in the design element list", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (final SQLException e) { // NOPMD - close quietly
                // close quietly
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (final SQLException e) { // NOPMD - close quietly
                // close quietly
            }
        }
    }
}

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 a2s  . co 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.bidtime.dbutils.QueryRunnerEx.java

/**
 * Calls update after checking the parameters to ensure nothing is null.
 * @param conn The connection to use for the batch call.
 * @param closeConn True if the connection should be closed, false otherwise.
 * @param sql The SQL statement to execute.
 * @param params An array of query replacement parameters.  Each row in
 * this array is one set of batch replacement values.
 * @return The number of rows updated in the batch.
 * @throws SQLException If there are database or parameter errors.
 *///w  w  w.  ja  va2 s  . c  o  m
private int[] batch(Connection conn, boolean closeConn, String sql, Object[][] params) throws SQLException {
    if (conn == null) {
        throw new SQLException("Null connection");
    }

    if (sql == null) {
        if (closeConn) {
            close(conn);
        }
        throw new SQLException("Null SQL statement");
    }

    if (params == null) {
        if (closeConn) {
            close(conn);
        }
        throw new SQLException("Null parameters. If parameters aren't need, pass an empty array.");
    }

    long startTime = System.currentTimeMillis();
    PreparedStatement stmt = null;
    int[] rows = null;
    try {
        stmt = this.prepareStatement(conn, sql);
        stmt.setQueryTimeout(StmtParams.getInstance().getStmtBatchTimeOut());
        for (int i = 0; i < params.length; i++) {
            this.fillStatement(stmt, params[i]);
            stmt.addBatch();
        }
        rows = stmt.executeBatch();
    } catch (SQLException e) {
        this.rethrow(e, sql, (Object[]) params);
    } finally {
        close(stmt);
        if (closeConn) {
            close(conn);
        }
        if (LogUpdateSql.logInfoOrDebug()) {
            LogUpdateSql.logFormatTimeNow(startTime, sql, params, (rows != null ? rows.length : 0));
        }
    }
    return rows;
}

From source file:org.wso2.carbon.device.mgt.extensions.device.type.template.dao.PropertyBasedPluginDAOImpl.java

public boolean updateDevice(Device device) throws DeviceTypeMgtPluginException {
    Connection conn;/*w  ww.j  a v  a 2 s.c  om*/
    PreparedStatement stmt = null;
    try {
        conn = deviceTypeDAOHandler.getConnection();
        stmt = conn.prepareStatement(
                "UPDATE DM_DEVICE_PROPERTIES SET PROPERTY_VALUE = ? WHERE  DEVICE_TYPE_NAME = ? AND "
                        + "DEVICE_IDENTIFICATION = ? AND PROPERTY_NAME = ? AND TENANT_ID= ?");

        for (Device.Property property : device.getProperties()) {
            if (!deviceProps.contains(property.getName())) {
                continue;
            }
            stmt.setString(1, property.getValue());
            stmt.setString(2, deviceType);
            stmt.setString(3, device.getDeviceIdentifier());
            stmt.setString(4, property.getName());
            stmt.setInt(5, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true));
            stmt.addBatch();
        }
        stmt.executeBatch();
        return true;
    } catch (SQLException e) {
        String msg = "Error occurred while modifying the device '" + device.getDeviceIdentifier() + "' data on"
                + deviceType;
        log.error(msg, e);
        throw new DeviceTypeMgtPluginException(msg, e);
    } finally {
        DeviceTypeUtils.cleanupResources(stmt, 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 {//from   w  w w.ja  va  2 s.  c om
        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:org.openbel.framework.core.kam.JdbcKAMLoaderImpl.java

/**
 * {@inheritDoc}/*from  w w  w  .  j a  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:org.wso2.carbon.is.migration.client.MigrateFrom520to530.java

/**
 * Check whether permission already assigned for role in UM_ROLE_PERMISSION Table
 *//* www.j  ava 2  s . c om*/
private boolean isPermissionAssignedForRole(Connection umConnection, String roleName, int permID, int isAllowed,
        int tenantId, int domainId) throws SQLException {

    boolean isExist = false;
    PreparedStatement countPermissions = umConnection
            .prepareStatement(SQLConstants.SELECT_ROLE_PERMISSION_COUNT);
    countPermissions.setInt(1, permID);
    countPermissions.setString(2, roleName);
    countPermissions.setInt(3, isAllowed);
    countPermissions.setInt(4, tenantId);
    countPermissions.setInt(5, domainId);
    countPermissions.addBatch();
    ResultSet countRS = countPermissions.executeQuery();
    if (countRS.next()) {
        int numberOfRows = countRS.getInt(1);
        if (numberOfRows > 0) {
            isExist = true;
        }
    }
    IdentityDatabaseUtil.closeResultSet(countRS);
    umConnection.commit();
    return isExist;
}

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

/**
 * {@inheritDoc}//from   www  .  ja  v  a  2  s  .c  om
 */
@Override
public void loadAnnotationDefinitionTypes() throws SQLException {
    int adtid = 0;

    PreparedStatement ps = getPreparedStatement(ANNOTATION_DEFINITION_TYPE_SQL);
    for (AnnotationType at : AnnotationType.values()) {
        String annotationTypeName = at.getDisplayValue();
        ps.setInt(1, adtid);
        ps.setString(2, annotationTypeName);
        ps.addBatch();
        adtid++;
    }

    // FIXME [Hack] add URL annotation type
    ps.setInt(1, AnnotationDefinitionTable.URL_ANNOTATION_TYPE_ID);
    ps.setString(2, AnnotationDefinitionTable.URL_ANNOTATION_TYPE);
    ps.addBatch();

    ps.executeBatch();
}