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.identity.application.mgt.dao.impl.ApplicationDAOImpl.java

/**
 * @param applicationId/*from w w w. j  ava 2s.c  o  m*/
 * @param authenticators
 * @param connection
 * @throws IdentityApplicationManagementException
 */
private void updateRequestPathAuthenticators(int applicationId, RequestPathAuthenticatorConfig[] authenticators,
        Connection connection) throws IdentityApplicationManagementException {

    int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    PreparedStatement storeReqPathAuthenticators = null;

    try {
        storeReqPathAuthenticators = connection
                .prepareStatement(ApplicationMgtDBQueries.STORE_REQ_PATH_AUTHENTICATORS);
        if (authenticators != null && authenticators.length > 0) {
            for (RequestPathAuthenticatorConfig auth : authenticators) {
                // TENANT_ID, AUTHENTICATOR_NAME, APP_ID
                storeReqPathAuthenticators.setInt(1, tenantID);
                storeReqPathAuthenticators.setString(2, CharacterEncoder.getSafeText(auth.getName()));
                storeReqPathAuthenticators.setInt(3, applicationId);
                storeReqPathAuthenticators.addBatch();
            }
            storeReqPathAuthenticators.executeBatch();
        }
    } catch (SQLException e) {
        throw new IdentityApplicationManagementException("Error while retrieving all application");
    } finally {
        IdentityApplicationManagementUtil.closeStatement(storeReqPathAuthenticators);
    }
}

From source file:org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationDAOImpl.java

/**
 * @param applicationID//from  w w  w  . ja v a2 s  . c  om
 * @param permissionsAndRoleConfiguration
 * @param connection
 * @throws SQLException
 */
private void updatePermissionAndRoleConfiguration(int applicationID,
        PermissionsAndRoleConfig permissionsAndRoleConfiguration, Connection connection) throws SQLException {

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

    RoleMapping[] roleMappings = permissionsAndRoleConfiguration.getRoleMappings();
    int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();

    PreparedStatement storeRoleMapPrepStmt = null;
    try {
        storeRoleMapPrepStmt = connection.prepareStatement(ApplicationMgtDBQueries.STORE_ROLE_MAPPING);
        for (RoleMapping roleMapping : roleMappings) {
            // TENANT_ID, IDP_ROLE, SP_ROLE, APP_ID
            storeRoleMapPrepStmt.setInt(1, tenantID);
            storeRoleMapPrepStmt.setString(2,
                    CharacterEncoder.getSafeText(roleMapping.getLocalRole().getLocalRoleName()));
            storeRoleMapPrepStmt.setString(3, CharacterEncoder.getSafeText(roleMapping.getRemoteRole()));
            storeRoleMapPrepStmt.setInt(4, applicationID);
            storeRoleMapPrepStmt.addBatch();

            if (debugMode) {
                log.debug("Storing Claim Mapping. IDPRole: " + roleMapping.getLocalRole() + " SPRole: "
                        + roleMapping.getRemoteRole());
            }
        }

        storeRoleMapPrepStmt.executeBatch();
    } finally {
        IdentityApplicationManagementUtil.closeStatement(storeRoleMapPrepStmt);
    }
}

From source file:com.viettel.logistic.wms.dao.StockGoodsSerialDAO.java

public List<GoodsSerialInforDTO> getGoodsBySerialInventory(OrdersDTO ordersDTO,
        List<GoodsSerialInforDTO> lstGoodsSerialInforDTO, Connection connection) {
    List<GoodsSerialInforDTO> lstGoodsReturn = new ArrayList();
    String message = ParamUtils.SUCCESS;
    String GOODS_IN_STOCK = "1,2";
    StringBuilder sqlInsertSerialTmp = new StringBuilder();
    StringBuilder sqlGetGoodsSerial = new StringBuilder();
    StringBuilder sqlGoodsNotEnough = new StringBuilder();
    StringBuilder sqlSerialDuplicate = new StringBuilder();
    StringBuilder sqlUpdateSerialWrong = new StringBuilder();
    PreparedStatement preparedStatement;
    ResultSet resultSet;//from  w w  w . j  a va2 s. c o  m
    GoodsSerialInforDTO serialInforDTO;
    List<String> lstDupplicateSerial = new ArrayList<>();
    try {
        //Insert serial vao bang tam
        sqlInsertSerialTmp.append(" INSERT INTO SERIAL_INVENTORY_TMP (cust_id,owner_id,owner_type,serial) ");
        sqlInsertSerialTmp.append(" VALUES (?,?,?,?)");
        preparedStatement = connection.prepareStatement(sqlInsertSerialTmp.toString());
        for (GoodsSerialInforDTO goodsSerialInforDTO : lstGoodsSerialInforDTO) {
            preparedStatement.setString(1, ordersDTO.getCustId());
            preparedStatement.setString(2, ordersDTO.getOrderStockId());
            preparedStatement.setString(3, ParamUtils.OWNER_TYPE.STOCK);
            preparedStatement.setString(4, goodsSerialInforDTO.getFromSerial().toUpperCase());
            //SET PARAMS FOR STOCK_TRANS_SERIAL                                        
            preparedStatement.addBatch();
        } //END FOR
          //Thuc thi batch
        preparedStatement.executeBatch();
        //ChuDV add 25/12/2015 --Cap nhat serial bo ky tu dau
        sqlUpdateSerialWrong.append(" UPDATE   serial_inventory_tmp ");
        sqlUpdateSerialWrong.append(" SET   serial = SUBSTR (serial, 2) ");
        sqlUpdateSerialWrong.append(" WHERE   serial IN ( ");
        sqlUpdateSerialWrong.append(" SELECT   UPPER(serial) ");
        sqlUpdateSerialWrong.append("   FROM   serial_inventory_tmp ");
        sqlUpdateSerialWrong.append(" MINUS ");
        sqlUpdateSerialWrong.append(" SELECT   UPPER(serial) ");
        sqlUpdateSerialWrong.append("   FROM   stock_goods_serial sgs ");
        sqlUpdateSerialWrong.append("  WHERE       sgs.cust_id = ? ");
        sqlUpdateSerialWrong.append("          AND sgs.owner_id = ? ");
        sqlUpdateSerialWrong.append("          AND sgs.owner_type = ? ");
        sqlUpdateSerialWrong.append("          AND sgs.status IN (1,2) ) ");
        sqlUpdateSerialWrong.append(" AND (serial like 'S%' OR serial like 's%') ");
        preparedStatement = connection.prepareCall(sqlUpdateSerialWrong.toString());
        preparedStatement.setString(1, ordersDTO.getCustId());
        preparedStatement.setString(2, ordersDTO.getOrderStockId());
        preparedStatement.setString(3, ParamUtils.OWNER_TYPE.STOCK);
        preparedStatement.executeUpdate();

        //Kiem tra hang thieu       
        sqlGoodsNotEnough.append(" SELECT   serial");
        sqlGoodsNotEnough.append("   FROM   serial_inventory_tmp ");
        sqlGoodsNotEnough.append(" MINUS ");
        sqlGoodsNotEnough.append(" SELECT   UPPER(serial) serial");
        sqlGoodsNotEnough.append("   FROM   stock_goods_serial sgs ");
        sqlGoodsNotEnough.append("  WHERE       sgs.cust_id = ? ");
        sqlGoodsNotEnough.append("          AND sgs.owner_id = ? ");
        sqlGoodsNotEnough.append("          AND sgs.owner_type = ? ");
        sqlGoodsNotEnough.append("          AND sgs.status IN (1,2) ");
        preparedStatement = connection.prepareCall(sqlGoodsNotEnough.toString());
        preparedStatement.setString(1, ordersDTO.getCustId());
        preparedStatement.setString(2, ordersDTO.getOrderStockId());
        preparedStatement.setString(3, ParamUtils.OWNER_TYPE.STOCK);
        //Lay ket qua query
        resultSet = preparedStatement.executeQuery();
        //                GoodsSerialInforDTO serialInforDTO;
        while (resultSet.next()) {
            serialInforDTO = new GoodsSerialInforDTO();
            serialInforDTO.setFromSerial(resultSet.getString("serial"));
            serialInforDTO.setToSerial(resultSet.getString("serial"));
            serialInforDTO.setNotes("SERIAL_MISSING");
            //                serialInforDTO.setCustId(ordersDTO.getCustId());
            //                serialInforDTO.setOwnerId(ordersDTO.getOrderStockId());
            lstGoodsReturn.add(serialInforDTO);
        }

        //Kiem tra trung
        sqlSerialDuplicate.append(" SELECT   st.serial");
        sqlSerialDuplicate.append("   FROM   goods g, serial_inventory_tmp st, stock_goods_serial sgs ");
        sqlSerialDuplicate.append("  WHERE       g.goods_id = sgs.goods_id ");
        sqlSerialDuplicate.append("          AND st.cust_id = sgs.cust_id ");
        sqlSerialDuplicate.append("          AND st.owner_id = sgs.owner_id ");
        sqlSerialDuplicate.append("          AND st.owner_type = sgs.owner_type ");
        sqlSerialDuplicate.append("          AND UPPER(st.serial) = UPPER(sgs.serial) ");
        sqlSerialDuplicate.append("          AND sgs.cust_id = ? ");
        sqlSerialDuplicate.append("          AND sgs.owner_id = ? ");
        sqlSerialDuplicate.append("          AND sgs.owner_type = ? ");
        sqlSerialDuplicate.append("          AND sgs.status IN (1,2) ");
        sqlSerialDuplicate.append("   GROUP BY   st.serial HAVING   COUNT ( * ) > 1 ");
        preparedStatement = connection.prepareCall(sqlSerialDuplicate.toString());
        preparedStatement.setString(1, ordersDTO.getCustId());
        preparedStatement.setString(2, ordersDTO.getOrderStockId());
        preparedStatement.setString(3, ParamUtils.OWNER_TYPE.STOCK);
        //Lay ket qua query
        resultSet = preparedStatement.executeQuery();
        //                GoodsSerialInforDTO serialInforDTO;
        while (resultSet.next()) {
            serialInforDTO = new GoodsSerialInforDTO();
            serialInforDTO.setFromSerial(resultSet.getString("serial"));
            serialInforDTO.setToSerial(resultSet.getString("serial"));
            serialInforDTO.setNotes("SERIAL_DUPPLICATE");
            lstDupplicateSerial.add(serialInforDTO.getFromSerial());
            //                serialInforDTO.setCustId(ordersDTO.getCustId());
            //                serialInforDTO.setOwnerId(ordersDTO.getOrderStockId());
            lstGoodsReturn.add(serialInforDTO);
        }

        //Lay danh sach hang hoa
        sqlGetGoodsSerial.append(" SELECT   g.goods_id goodsId, ");
        sqlGetGoodsSerial.append("          g.code goodsCode, ");
        sqlGetGoodsSerial.append("          g.name goodsName, ");
        sqlGetGoodsSerial.append("          g.unit_type unitType, ");
        sqlGetGoodsSerial.append("          sgs.barcode barcode, ");
        sqlGetGoodsSerial.append("          st.serial serial, ");
        sqlGetGoodsSerial.append("          sgs.goods_state goodsState, ");
        sqlGetGoodsSerial.append("          sgs.cell_code cellCode ");
        sqlGetGoodsSerial.append("   FROM   goods g, serial_inventory_tmp st, stock_goods_serial sgs ");
        sqlGetGoodsSerial.append("  WHERE       g.goods_id = sgs.goods_id ");
        sqlGetGoodsSerial.append("          AND st.cust_id = sgs.cust_id ");
        sqlGetGoodsSerial.append("          AND st.owner_id = sgs.owner_id ");
        sqlGetGoodsSerial.append("          AND st.owner_type = sgs.owner_type ");
        sqlGetGoodsSerial.append("          AND UPPER(st.serial) = UPPER(sgs.serial) ");
        sqlGetGoodsSerial.append("          AND sgs.cust_id = ? ");
        sqlGetGoodsSerial.append("          AND sgs.owner_id = ? ");
        sqlGetGoodsSerial.append("          AND sgs.owner_type = ? ");
        sqlGetGoodsSerial.append("          AND sgs.status IN (1,2) ");
        sqlGetGoodsSerial.append("  ORDER BY goodsCode, goodsState, serial ");

        preparedStatement = connection.prepareCall(sqlGetGoodsSerial.toString());
        preparedStatement.setString(1, ordersDTO.getCustId());
        preparedStatement.setString(2, ordersDTO.getOrderStockId());
        preparedStatement.setString(3, ParamUtils.OWNER_TYPE.STOCK);
        //Lay ket qua query
        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            serialInforDTO = new GoodsSerialInforDTO();
            serialInforDTO.setGoodsId(resultSet.getString("goodsId"));
            serialInforDTO.setGoodsCode(resultSet.getString("goodsCode"));
            serialInforDTO.setGoodsName(resultSet.getString("goodsName"));
            serialInforDTO.setGoodsState(resultSet.getString("goodsState"));
            serialInforDTO.setCellCode(resultSet.getString("cellCode"));
            serialInforDTO.setBarcode(resultSet.getString("barcode"));
            serialInforDTO.setFromSerial(resultSet.getString("serial"));
            serialInforDTO.setToSerial(resultSet.getString("serial"));
            serialInforDTO.setUnitType(resultSet.getString("unitType"));
            serialInforDTO.setQuantity("1");
            if (lstDupplicateSerial.contains(serialInforDTO.getFromSerial())) {
                serialInforDTO.setNotes("SERIAL_DUPPLICATE");
            }
            //                serialInforDTO.setCustId(ordersDTO.getCustId());
            //                serialInforDTO.setOwnerId(ordersDTO.getOrderStockId());
            lstGoodsReturn.add(serialInforDTO);
        }
        preparedStatement.close();
    } catch (Exception e) {
        message = ParamUtils.FAIL;
        lstGoodsReturn = new ArrayList<>();
        e.printStackTrace();
    }
    return lstGoodsReturn;
}

From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java

@Override
public void batchInsertMessageContent(MessageContent messageContent) {
    logger.debug(messageContent.getChannelId() + "/" + messageContent.getMessageId() + "/"
            + messageContent.getMetaDataId() + ": batch inserting message content ("
            + messageContent.getContentType().toString() + ")");

    try {// w  w  w.ja v a 2s  .  c om
        String content;
        boolean encrypted;

        // Only encrypt if the content is not already encrypted
        if (encryptData && encryptor != null && !messageContent.isEncrypted()) {
            content = encryptor.encrypt(messageContent.getContent());
            encrypted = true;
        } else {
            content = messageContent.getContent();
            encrypted = messageContent.isEncrypted();
        }

        PreparedStatement statement = prepareStatement("batchInsertMessageContent",
                messageContent.getChannelId());
        statement.setInt(1, messageContent.getMetaDataId());
        statement.setLong(2, messageContent.getMessageId());
        statement.setInt(3, messageContent.getContentType().getContentTypeCode());
        statement.setString(4, content);
        statement.setString(5, messageContent.getDataType());
        statement.setBoolean(6, encrypted);

        statement.addBatch();
        statement.clearParameters();
    } catch (SQLException e) {
        throw new DonkeyDaoException(e);
    }
}

From source file:org.obm.domain.dao.CalendarDaoJdbcImpl.java

private Event removeEventByExtId(Connection con, ObmUser calendar, AccessToken token, EventExtId extId) {
    Event ev = findEventByExtId(token, calendar, extId);
    if (ev == null) {
        return null;
    }/*  w w w.  j a  v a2s.c  o  m*/
    PreparedStatement dev = null;
    try {
        dev = con.prepareStatement(
                "INSERT INTO DeletedEvent (deletedevent_event_id, deletedevent_user_id, deletedevent_origin, deletedevent_timestamp, deletedevent_event_ext_id) "
                        + "VALUES (?, ?, ?, now(), ?)");
        EventObmId databaseId = ev.getObmId();
        for (Attendee at : ev.getAttendees()) {
            Integer userId = userDao.userIdFromEmail(con, at.getEmail(), token.getDomain().getId());
            if (userId != null) {
                dev.setInt(1, databaseId.getObmId());
                dev.setInt(2, userId);
                dev.setString(3, token.getOrigin());
                dev.setString(4, extId.getExtId());
                dev.addBatch();
            }
        }
        dev.executeBatch();
        dev.close();

        removeEventExceptions(con, databaseId);

        dev = con.prepareStatement("DELETE FROM Event WHERE event_id=?");
        dev.setInt(1, databaseId.getObmId());
        dev.executeUpdate();
        if (dev.getUpdateCount() <= 0) {
            throw new EventNotFoundException("Unexpected Event deletion failure : " + databaseId.getObmId());
        }
    } catch (Throwable se) {
        logger.error(se.getMessage(), se);
    } finally {
        obmHelper.cleanup(null, dev, null);
    }

    return ev;
}

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

private Event removeEventByExtId(Connection con, ObmUser calendar, AccessToken token, EventExtId extId) {
    Event ev = findEventByExtId(token, calendar, extId);
    if (ev == null) {
        return null;
    }/*from www  . jav  a2s. c  o  m*/
    PreparedStatement dev = null;
    try {
        dev = con.prepareStatement(
                "INSERT INTO DeletedEvent (deletedevent_event_id, deletedevent_user_id, deletedevent_origin, deletedevent_timestamp, deletedevent_event_ext_id) "
                        + "VALUES (?, ?, ?, now(), ?)");
        EventObmId databaseId = ev.getObmId();
        for (Attendee at : ev.getAttendees()) {
            Integer userId = userDao.userIdFromEmail(con, at.getEmail(), token.getDomain().getId());
            if (userId != null) {
                dev.setInt(1, databaseId.getObmId());
                dev.setInt(2, userId);
                dev.setString(3, token.getOrigin());
                dev.setString(4, extId.getExtId());
                dev.addBatch();
            }
        }
        dev.executeBatch();
        dev.close();

        removeEventExceptions(con, databaseId);

        dev = con.prepareStatement("DELETE FROM Event WHERE event_id=?");
        dev.setInt(1, databaseId.getObmId());
        dev.executeUpdate();

    } catch (Throwable se) {
        logger.error(se.getMessage(), se);
    } finally {
        obmHelper.cleanup(null, dev, null);
    }

    return ev;
}

From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java

/**
 * This should run on server close, so we don't need to synchronize as every player join is denied before.
 *
 * @param connection MySQL connection//from  www .  j a v a  2s. c o m
 * @throws SQLException in case of something going wrong
 */
private void saveChangedPlayers(@NotNull Connection connection) throws SQLException {
    long start = System.nanoTime();
    int numberOfPlayersUpdated = 0;

    // Prepare statement
    PreparedStatement preparedStatement = connection.prepareStatement(
            "UPDATE `minecraft`.`user_profiles` SET `playerName` = ?, `password` = ?, `moneyAmount` = ?, `city_cityId` = ?,"
                    + " `cityOccupation` = ?, `lastTimeOnline` = ?, `timePlayed` = ?, `lastIp` = ? WHERE `playerId` = ?;");

    // Iterate through all players
    for (OfflinePlayer offlinePlayer : registeredOfflinePlayers_id.values())
        // Filter the ones needing updates => REGISTERED PLAYERS: they have money amount, passwords, last time online, last IP
        if (offlinePlayer.getDatabaseState() == DatabaseState.UPDATE_DATABASE) {
            preparedStatement.setString(1, offlinePlayer.getPlayerName());
            preparedStatement.setString(2, offlinePlayer.getEncryptedPassword());
            preparedStatement.setDouble(3, offlinePlayer.getMoneyAmount());
            preparedStatement.setObject(4, offlinePlayer.getCityId(), Types.INTEGER); // Will write null if is null
            preparedStatement.setObject(5,
                    offlinePlayer.getCityOccupation() != null
                            ? offlinePlayer.getCityOccupation().getOccupationId()
                            : null,
                    Types.TINYINT);
            preparedStatement.setLong(6, offlinePlayer.getLastTimeOnline());
            preparedStatement.setLong(7, offlinePlayer.getTimePlayed());
            preparedStatement.setString(8, offlinePlayer.getLastIp());
            preparedStatement.setLong(9, offlinePlayer.getPlayerId());

            // Add batch
            preparedStatement.addBatch();

            // Update their database state
            offlinePlayer.databaseState = DatabaseState.ON_DATABASE;
            numberOfPlayersUpdated++;
        }

    // Execute and announce
    if (numberOfPlayersUpdated > 0) {
        preparedStatement.executeBatch();
        LobsterCraft.logger.info(Util.appendStrings("Took us ",
                Util.formatDecimal(
                        (double) (System.nanoTime() - start) / (double) TimeUnit.MILLISECONDS.toNanos(1)),
                "ms to update ", numberOfPlayersUpdated, " players."));
    }

    // Close statement
    preparedStatement.close();
}

From source file:org.linqs.psl.database.rdbms.RDBMSInserter.java

private void insertInternal(List<Double> values, List<List<Object>> data) {
    assert (values.size() == data.size());

    int partitionID = partition.getID();
    if (partitionID < 0) {
        throw new IllegalArgumentException("Partition IDs must be non-negative.");
    }/* www  .jav  a 2 s .  co  m*/

    for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
        List<Object> row = data.get(rowIndex);

        assert (row != null);

        if (row.size() != predicateInfo.argumentColumns().size()) {
            throw new IllegalArgumentException(
                    String.format("Data on row %d length does not match for %s: Expecting: %d, Got: %d",
                            rowIndex, partition.getName(), predicateInfo.argumentColumns().size(), row.size()));
        }
    }

    try (Connection connection = dataStore.getConnection();
            PreparedStatement multiInsertStatement = connection.prepareStatement(multiInsertSQL);
            PreparedStatement singleInsertStatement = connection.prepareStatement(singleInsertSQL);) {
        int batchSize = 0;

        // We will go from the multi-insert to the single-insert when we don't have enough data to fill the multi-insert.
        PreparedStatement activeStatement = multiInsertStatement;
        int insertSize = DEFAULT_MULTIROW_COUNT;

        int rowIndex = 0;
        while (rowIndex < data.size()) {
            // Index for the current index.
            int paramIndex = 1;

            if (activeStatement == multiInsertStatement && data.size() - rowIndex < DEFAULT_MULTIROW_COUNT) {
                // Commit any records left in the multi-insert batch.
                if (batchSize > 0) {
                    activeStatement.executeBatch();
                    activeStatement.clearBatch();
                    batchSize = 0;
                }

                activeStatement = singleInsertStatement;
                insertSize = 1;
            }

            for (int i = 0; i < insertSize; i++) {
                List<Object> row = data.get(rowIndex);
                Double value = values.get(rowIndex);

                // Partition
                activeStatement.setInt(paramIndex++, partitionID);

                // Value
                if (value == null || value.isNaN()) {
                    activeStatement.setNull(paramIndex++, java.sql.Types.DOUBLE);
                } else {
                    activeStatement.setDouble(paramIndex++, value);
                }

                for (int argIndex = 0; argIndex < predicateInfo.argumentColumns().size(); argIndex++) {
                    Object argValue = row.get(argIndex);

                    assert (argValue != null);

                    if (argValue instanceof Integer) {
                        activeStatement.setInt(paramIndex++, (Integer) argValue);
                    } else if (argValue instanceof Double) {
                        // The standard JDBC way to insert NaN is using setNull
                        if (Double.isNaN((Double) argValue)) {
                            activeStatement.setNull(paramIndex++, java.sql.Types.DOUBLE);
                        } else {
                            activeStatement.setDouble(paramIndex++, (Double) argValue);
                        }
                    } else if (argValue instanceof String) {
                        // This is the most common value we get when someone is using InsertUtils.
                        // The value may need to be convered from a string.
                        activeStatement.setObject(paramIndex++, convertString((String) argValue, argIndex));
                    } else if (argValue instanceof UniqueIntID) {
                        activeStatement.setInt(paramIndex++, ((UniqueIntID) argValue).getID());
                    } else if (argValue instanceof UniqueStringID) {
                        activeStatement.setString(paramIndex++, ((UniqueStringID) argValue).getID());
                    } else {
                        throw new IllegalArgumentException("Unknown data type for :" + argValue);
                    }
                }

                rowIndex++;
            }

            activeStatement.addBatch();
            batchSize++;

            if (batchSize >= DEFAULT_PAGE_SIZE) {
                activeStatement.executeBatch();
                activeStatement.clearBatch();
                batchSize = 0;
            }
        }

        if (batchSize > 0) {
            activeStatement.executeBatch();
            activeStatement.clearBatch();
            batchSize = 0;
        }
        activeStatement.clearParameters();
        activeStatement = null;
    } catch (SQLException ex) {
        log.error(ex.getMessage());
        throw new RuntimeException("Error inserting into RDBMS.", ex);
    }
}

From source file:org.hyperic.hq.measurement.server.session.DataManagerImpl.java

private boolean insertTopData(Connection conn, List<TopNData> topNData, boolean continueOnSQLException)
        throws SQLException {
    if (log.isDebugEnabled()) {
        log.debug("Inserting Top Processes data - '" + topNData + "'");
    }//from w ww . j  a va  2s  .co  m
    PreparedStatement stmt = null;
    final StringBuilder buf = new StringBuilder();

    Map<Date, List<TopNData>> dayToDataMap = mapDayToData(topNData);

    for (Entry<Date, List<TopNData>> entry : dayToDataMap.entrySet()) {
        try {

            String partitionName = getAndCreatePartition(TopNData.class.getSimpleName(), entry.getKey(), conn);
            stmt = conn.prepareStatement(buf.append("INSERT INTO ").append(partitionName)
                    .append(" (resourceId, time, data) VALUES (?, ?, ?)").toString());

            for (TopNData data : entry.getValue()) {
                stmt.setInt(1, data.getResourceId());
                stmt.setTimestamp(2, new java.sql.Timestamp(data.getTime().getTime()));
                stmt.setBytes(3, data.getData());
                stmt.addBatch();
            }
            int[] execInfo = stmt.executeBatch();

        } catch (BatchUpdateException e) {
            if (!continueOnSQLException) {
                throw e;
            }
        } catch (SQLException e) {
            if (!continueOnSQLException) {
                throw e;
            }
            if (log.isDebugEnabled()) {
                log.debug("A general SQLException occurred during the insert of TopN. ", e);
            }

        } finally {
            DBUtil.closeStatement(LOG_CTX, stmt);
        }

    }
    return true;
}

From source file:org.rimudb.Table.java

/**
 * /*from   w w  w  .jav a2s  .  c  o m*/
 * @param session Session
 * @param oldRecord Record
 * @param newRecord Record
 * @throws RimuDBException
 */
public void updateRecordInBatch(Session session, Record oldRecord, Record newRecord) throws RimuDBException {
    PreparedStatement stmt = null;
    int statID = 0;

    try {
        List<String> changedPropertyList = newRecord.getModifiedProperties();
        List<String> nulledProperties = oldRecord.getNulledProperties();

        // Throws an exception if one of the changed properties is a PK and its being changed to a null
        tableMetaData.checkForNulledPrimaryKey(newRecord.getModifiedToNullProperties());

        List<String> nullColumnList = tableMetaData.getColumnNamesFromPropertyNames(nulledProperties);

        String sql = sqlStatementCache.getUpdatePKSQL(getOptimisticLocking(), changedPropertyList,
                nullColumnList);
        if (sql == null) {
            sql = sqlAdapter.getPrimaryKeyUpdateStatement(tableMetaData, getTableName(), getOptimisticLocking(),
                    changedPropertyList, nullColumnList);
            sqlStatementCache.addUpdatePKSQL(getOptimisticLocking(), changedPropertyList, nullColumnList, sql);
        }

        // Get the statistic ID
        int loggingType = getDatabase().getDatabaseConfiguration().getLoggingType();
        if (loggingType == DatabaseConfiguration.LOG_STATISTICS) {
            statID = StatisticCollector.getInstance().createStatistic(sql);
        } else if (loggingType == DatabaseConfiguration.LOG_SQL_ONLY) {
            log.info("SQL=" + sql);
        }

        stmt = session.getBatchStatement(this, Session.BATCH_UPDATE);
        if (stmt == null) {
            stmt = createPreparedStatement(session.getConnection(), sql, CrudType.UPDATE);
            session.setBatchStatement(this, stmt, Session.BATCH_UPDATE);
        }

        recordBinder.bindStatementForUpdate(stmt, oldRecord, newRecord, getOptimisticLocking(),
                changedPropertyList);

        if (statID > 0)
            StatisticCollector.getInstance().logEvent(statID, "preparetime");

        stmt.addBatch();

        if (statID > 0)
            StatisticCollector.getInstance().logEvent(statID, "executetime");

        if (statID > 0) {
            StatisticCollector.getInstance().logEvent(statID, "processtime");
            if (StatisticCollector.getInstance().exceedsThreshold(statID,
                    getDatabase().getDatabaseConfiguration().getLoggingThreshold())) {
                String text = StatisticCollector.getInstance().formatStatistics(statID,
                        getDatabase().getStatisticFormatter());
                log.info(text);
            }
            StatisticCollector.getInstance().removeID(statID);
        }

    } catch (SQLException e) {

        throw new RimuDBException(e);

    }
}