Example usage for java.sql PreparedStatement setFloat

List of usage examples for java.sql PreparedStatement setFloat

Introduction

In this page you can find the example usage for java.sql PreparedStatement setFloat.

Prototype

void setFloat(int parameterIndex, float x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java float value.

Usage

From source file:info.raack.appliancelabeler.data.JDBCDatabase.java

public void storeData(final EnergyMonitor energyMonitor, final List<SecondData> data, final Long lastOffset) {
    // check to see if we need a new row in energy_monitor
    final String userId = energyMonitor.getUserId();

    final String monitorId = energyMonitor.getMonitorId();
    final String monitorType = energyMonitor.getType();

    int tempEnergyMonitorId = getIdForEnergyMonitor(energyMonitor);

    final int energyMonitorId = tempEnergyMonitorId;

    // save the batch
    long timestart = System.currentTimeMillis();

    // don't insert more than a million rows at a time

    boolean lastLoop = false;
    for (int j = 0; lastLoop != true; j++) {
        final List<SecondData> tempData = new ArrayList<SecondData>();

        final int MAX_INSERTS = 2000000;

        int start = j * MAX_INSERTS;

        if (data.size() < (j + 1) * MAX_INSERTS) {
            // remaining data is less than 1 million rows
            int end = data.size();
            logger.debug("Inserting records from " + start + " to " + end);
            tempData.addAll(data.subList(start, end));
            lastLoop = true;//  w  w  w .  j  ava2  s. c  o m
        } else {
            int end = (j + 1) * MAX_INSERTS;
            logger.debug("Inserting records from " + start + " to " + end);
            tempData.addAll(data.subList(start, end));
        }

        logger.debug("Inserting " + tempData.size() + " energy measurements for " + userId);
        jdbcTemplate.batchUpdate(insertNewEnergyReadings, new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement ps, int i) throws SQLException {

                SecondData secondData = tempData.get(i);

                if (i % 10000 == 0) {
                    logger.debug("Preparing for record " + i);
                }

                ps.setInt(1, energyMonitorId);
                ps.setLong(2, secondData.getCalLong());
                ps.setInt(3, secondData.getPower());
                ps.setFloat(4, secondData.getVoltage());
            }

            public int getBatchSize() {
                return tempData.size();
            }
        });
    }
    long timestop = System.currentTimeMillis();
    float total = (timestop - timestart) / 1000;
    logger.debug("Inserting " + data.size() + " rows into database took " + total + " seconds; "
            + (data.size() / total) + " rows per second");

    jdbcTemplate.update(updateLastOffset, new Object[] { lastOffset, userId, monitorId });
}

From source file:org.owasp.dependencycheck.data.nvdcve.CveDB.java

/**
 * Updates the vulnerability within the database. If the vulnerability does
 * not exist it will be added.// w ww.  j  a v a  2 s.  com
 *
 * @param vuln the vulnerability to add to the database
 * @throws DatabaseException is thrown if the database
 */
public synchronized void updateVulnerability(Vulnerability vuln) throws DatabaseException {
    clearCache();
    ResultSet rs = null;
    try {
        int vulnerabilityId = 0;
        final PreparedStatement selectVulnerabilityId = getPreparedStatement(SELECT_VULNERABILITY_ID);
        selectVulnerabilityId.setString(1, vuln.getName());
        rs = selectVulnerabilityId.executeQuery();
        if (rs.next()) {
            vulnerabilityId = rs.getInt(1);
            // first delete any existing vulnerability info. We don't know what was updated. yes, slower but atm easier.
            final PreparedStatement deleteReference = getPreparedStatement(DELETE_REFERENCE);
            deleteReference.setInt(1, vulnerabilityId);
            deleteReference.execute();

            final PreparedStatement deleteSoftware = getPreparedStatement(DELETE_SOFTWARE);
            deleteSoftware.setInt(1, vulnerabilityId);
            deleteSoftware.execute();
        }

        DBUtils.closeResultSet(rs);

        if (vulnerabilityId != 0) {
            if (vuln.getDescription().contains("** REJECT **")) {
                final PreparedStatement deleteVulnerability = getPreparedStatement(DELETE_VULNERABILITY);
                deleteVulnerability.setInt(1, vulnerabilityId);
                deleteVulnerability.executeUpdate();
            } else {
                final PreparedStatement updateVulnerability = getPreparedStatement(UPDATE_VULNERABILITY);
                updateVulnerability.setString(1, vuln.getDescription());
                updateVulnerability.setString(2, vuln.getCwe());
                updateVulnerability.setFloat(3, vuln.getCvssScore());
                updateVulnerability.setString(4, vuln.getCvssAccessVector());
                updateVulnerability.setString(5, vuln.getCvssAccessComplexity());
                updateVulnerability.setString(6, vuln.getCvssAuthentication());
                updateVulnerability.setString(7, vuln.getCvssConfidentialityImpact());
                updateVulnerability.setString(8, vuln.getCvssIntegrityImpact());
                updateVulnerability.setString(9, vuln.getCvssAvailabilityImpact());
                updateVulnerability.setInt(10, vulnerabilityId);
                updateVulnerability.executeUpdate();
            }
        } else {
            final PreparedStatement insertVulnerability = getPreparedStatement(INSERT_VULNERABILITY);
            insertVulnerability.setString(1, vuln.getName());
            insertVulnerability.setString(2, vuln.getDescription());
            insertVulnerability.setString(3, vuln.getCwe());
            insertVulnerability.setFloat(4, vuln.getCvssScore());
            insertVulnerability.setString(5, vuln.getCvssAccessVector());
            insertVulnerability.setString(6, vuln.getCvssAccessComplexity());
            insertVulnerability.setString(7, vuln.getCvssAuthentication());
            insertVulnerability.setString(8, vuln.getCvssConfidentialityImpact());
            insertVulnerability.setString(9, vuln.getCvssIntegrityImpact());
            insertVulnerability.setString(10, vuln.getCvssAvailabilityImpact());
            insertVulnerability.execute();
            try {
                rs = insertVulnerability.getGeneratedKeys();
                rs.next();
                vulnerabilityId = rs.getInt(1);
            } catch (SQLException ex) {
                final String msg = String.format("Unable to retrieve id for new vulnerability for '%s'",
                        vuln.getName());
                throw new DatabaseException(msg, ex);
            } finally {
                DBUtils.closeResultSet(rs);
            }
        }

        PreparedStatement insertReference = getPreparedStatement(INSERT_REFERENCE);
        int countReferences = 0;
        for (Reference r : vuln.getReferences()) {
            insertReference.setInt(1, vulnerabilityId);
            insertReference.setString(2, r.getName());
            insertReference.setString(3, r.getUrl());
            insertReference.setString(4, r.getSource());
            if (isBatchInsertEnabled()) {
                insertReference.addBatch();
                countReferences++;
                if (countReferences % getBatchSize() == 0) {
                    insertReference.executeBatch();
                    insertReference = getPreparedStatement(INSERT_REFERENCE);
                    LOGGER.trace(getLogForBatchInserts(countReferences,
                            "Completed %s batch inserts to references table: %s"));
                    countReferences = 0;
                } else if (countReferences == vuln.getReferences().size()) {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace(getLogForBatchInserts(countReferences,
                                "Completed %s batch inserts to reference table: %s"));
                    }
                    insertReference.executeBatch();
                    countReferences = 0;
                }
            } else {
                insertReference.execute();
            }
        }

        PreparedStatement insertSoftware = getPreparedStatement(INSERT_SOFTWARE);
        int countSoftware = 0;
        for (VulnerableSoftware vulnerableSoftware : vuln.getVulnerableSoftware()) {
            int cpeProductId = 0;
            final PreparedStatement selectCpeId = getPreparedStatement(SELECT_CPE_ID);
            selectCpeId.setString(1, vulnerableSoftware.getName());
            try {
                rs = selectCpeId.executeQuery();
                if (rs.next()) {
                    cpeProductId = rs.getInt(1);
                }
            } catch (SQLException ex) {
                throw new DatabaseException(
                        "Unable to get primary key for new cpe: " + vulnerableSoftware.getName(), ex);
            } finally {
                DBUtils.closeResultSet(rs);
            }

            if (cpeProductId == 0) {
                final PreparedStatement insertCpe = getPreparedStatement(INSERT_CPE);
                insertCpe.setString(1, vulnerableSoftware.getName());
                insertCpe.setString(2, vulnerableSoftware.getVendor());
                insertCpe.setString(3, vulnerableSoftware.getProduct());
                insertCpe.executeUpdate();
                cpeProductId = DBUtils.getGeneratedKey(insertCpe);
            }
            if (cpeProductId == 0) {
                throw new DatabaseException("Unable to retrieve cpeProductId - no data returned");
            }

            insertSoftware.setInt(1, vulnerabilityId);
            insertSoftware.setInt(2, cpeProductId);

            if (vulnerableSoftware.getPreviousVersion() == null) {
                insertSoftware.setNull(3, java.sql.Types.VARCHAR);
            } else {
                insertSoftware.setString(3, vulnerableSoftware.getPreviousVersion());
            }
            if (isBatchInsertEnabled()) {
                insertSoftware.addBatch();
                countSoftware++;
                if (countSoftware % getBatchSize() == 0) {
                    executeBatch(vuln, vulnerableSoftware, insertSoftware);
                    insertSoftware = getPreparedStatement(INSERT_SOFTWARE);
                    LOGGER.trace(getLogForBatchInserts(countSoftware,
                            "Completed %s batch inserts software table: %s"));
                    countSoftware = 0;
                } else if (countSoftware == vuln.getVulnerableSoftware().size()) {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace(getLogForBatchInserts(countSoftware,
                                "Completed %s batch inserts software table: %s"));
                        countReferences = 0;
                    }
                    executeBatch(vuln, vulnerableSoftware, insertSoftware);
                }
            } else {
                try {
                    insertSoftware.execute();
                } catch (SQLException ex) {
                    if (ex.getMessage().contains("Duplicate entry")) {
                        final String msg = String.format("Duplicate software key identified in '%s:%s'",
                                vuln.getName(), vuln.getName());
                        LOGGER.info(msg, ex);
                    } else {
                        throw ex;
                    }
                }
            }
        }
    } catch (SQLException ex) {
        final String msg = String.format("Error updating '%s'", vuln.getName());
        LOGGER.debug(msg, ex);
        throw new DatabaseException(msg, ex);
    } finally {
        DBUtils.closeResultSet(rs);
    }
}

From source file:com.thinkmore.framework.orm.hibernate.SimpleHibernateDao.java

public void setParameters(PreparedStatement ps, int j, Object value) throws SQLException {
    if (value != null) {
        if (value instanceof java.lang.Integer) {
            ps.setInt(j, (Integer) value);
        } else if (value instanceof java.lang.Long) {
            ps.setLong(j, (Long) value);
        } else if (value instanceof java.util.Date) {
            ps.setTimestamp(j, new java.sql.Timestamp(((Date) value).getTime()));
        } else if (value instanceof java.sql.Date) {
            ps.setDate(j, new java.sql.Date(((Date) value).getTime()));
        } else if (value instanceof java.lang.String) {
            ps.setString(j, value.toString());
        } else if (value instanceof java.lang.Double) {
            ps.setDouble(j, (Double) value);
        } else if (value instanceof java.lang.Byte) {
            ps.setByte(j, (Byte) value);
        } else if (value instanceof java.lang.Character) {
            ps.setString(j, value.toString());
        } else if (value instanceof java.lang.Float) {
            ps.setFloat(j, (Float) value);
        } else if (value instanceof java.lang.Boolean) {
            ps.setBoolean(j, (Boolean) value);
        } else if (value instanceof java.lang.Short) {
            ps.setShort(j, (Short) value);
        } else {/*from   ww  w .  java 2 s. c  o m*/
            ps.setObject(j, value);
        }
    } else {
        ps.setNull(j, Types.NULL);
    }
}

From source file:mysql5.MySQL5PlayerDAO.java

/**
 * {@inheritDoc}//from  ww w  .  j ava 2  s .  c  om
 */
@Override
public boolean saveNewPlayer(final PlayerCommonData pcd, final int accountId, final String accountName) {
    Connection con = null;
    try {
        con = DatabaseFactory.getConnection();
        PreparedStatement preparedStatement = con.prepareStatement(
                "INSERT INTO players(id, `name`, account_id, account_name, x, y, z, heading, world_id, gender, race, player_class , quest_expands, npc_expands, warehouse_size, online) "
                        + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)");

        log.debug("[DAO: MySQL5PlayerDAO] saving new player: " + pcd.getPlayerObjId() + " " + pcd.getName());

        preparedStatement.setInt(1, pcd.getPlayerObjId());
        preparedStatement.setString(2, pcd.getName());
        preparedStatement.setInt(3, accountId);
        preparedStatement.setString(4, accountName);
        preparedStatement.setFloat(5, pcd.getPosition().getX());
        preparedStatement.setFloat(6, pcd.getPosition().getY());
        preparedStatement.setFloat(7, pcd.getPosition().getZ());
        preparedStatement.setInt(8, pcd.getPosition().getHeading());
        preparedStatement.setInt(9, pcd.getPosition().getMapId());
        preparedStatement.setString(10, pcd.getGender().toString());
        preparedStatement.setString(11, pcd.getRace().toString());
        preparedStatement.setString(12, pcd.getPlayerClass().toString());
        preparedStatement.setInt(13, pcd.getQuestExpands());
        preparedStatement.setInt(14, pcd.getNpcExpands());
        preparedStatement.setInt(15, pcd.getWarehouseSize());
        preparedStatement.execute();
        preparedStatement.close();
    } catch (Exception e) {
        log.error("Error saving new player: " + pcd.getPlayerObjId() + " " + pcd.getName(), e);
        return false;
    } finally {
        DatabaseFactory.close(con);
    }
    if (CacheConfig.CACHE_COMMONDATA) {
        playerCommonData.put(pcd.getPlayerObjId(), pcd);
        playerCommonDataByName.put(pcd.getName().toLowerCase(), pcd);
    }
    return true;
}

From source file:nl.tudelft.stocktrader.derby.DerbyMarketSummaryDAO.java

public void updateStockPriceVolume(double quantity, RemoteQuoteData quote) throws DAOException {
    //      BigDecimal priceChangeFactor = StockTraderUtility.getRandomPriceChangeFactor(quote.getPrice());
    //      BigDecimal newPrice = quote.getPrice().multiply(priceChangeFactor);
    ////from  ww w.j av a2s .c o  m
    //      if (newPrice.compareTo(quote.getLow()) == -1) {
    //         quote.setLow(newPrice);
    //      }
    //      if (newPrice.compareTo(quote.getHigh()) == 1) {
    //         quote.setHigh(newPrice);
    //      }

    PreparedStatement previousValues = null;
    PreparedStatement updateStockPriceVolumeStat = null;
    try {
        previousValues = sqlConnection.prepareStatement(SQL_SELECT_QUOTE);
        previousValues.setString(1, quote.getTicker());
        ResultSet rs = previousValues.executeQuery();

        if (!rs.next()) {
            throw new DAOException("Could not find quote " + quote.getTicker());
        }

        double low = rs.getDouble("low");
        double high = rs.getDouble("high");

        if (low > quote.getValue()) {
            low = quote.getValue();
        }

        if (high < quote.getValue()) {
            high = quote.getValue();
        }

        BigDecimal value = new BigDecimal(quote.getValue()).setScale(4, RoundingMode.HALF_UP);

        updateStockPriceVolumeStat = sqlConnection.prepareStatement(SQL_UPDATE_STOCKPRICEVOLUME);
        updateStockPriceVolumeStat.setBigDecimal(1, value);
        updateStockPriceVolumeStat.setBigDecimal(2, new BigDecimal(low).setScale(4, RoundingMode.HALF_UP));
        updateStockPriceVolumeStat.setBigDecimal(3, new BigDecimal(high).setScale(4, RoundingMode.HALF_UP));
        updateStockPriceVolumeStat.setBigDecimal(4, value);
        updateStockPriceVolumeStat.setFloat(5, (float) quantity);
        updateStockPriceVolumeStat.setString(6, quote.getTicker());
        updateStockPriceVolumeStat.executeUpdate();

    } catch (SQLException e) {
        throw new DAOException("", e);
    } finally {
        try {
            if (updateStockPriceVolumeStat != null) {
                updateStockPriceVolumeStat.close();
            }
        } catch (SQLException e) {
            logger.debug("", e);
        }
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

private void setPreparedValue(final PreparedStatement pstmnt, final int index,
        final StructAttributeReflect attr, Object value, final AbstractEntity entity) throws Exception {
    Class<?> type = attr.Field.getType();
    if (EnumPrimitives.isPrimitiveType(type)) {
        EnumPrimitives prim = EnumPrimitives.type(type);
        switch (prim) {
        case ECharacter:
            pstmnt.setString(index, String.valueOf(value));
            break;
        case EShort:
            pstmnt.setShort(index, (Short) value);
            break;
        case EInteger:
            pstmnt.setInt(index, (Integer) value);
            break;
        case ELong:
            pstmnt.setLong(index, (Long) value);
            break;
        case EFloat:
            pstmnt.setFloat(index, (Float) value);
            break;
        case EDouble:
            pstmnt.setDouble(index, (Double) value);
            break;
        default://from  w  w  w  .  ja  v a 2s .  co  m
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else {
        if (type.equals(String.class)) {
            pstmnt.setString(index, (String) value);
        } else if (type.equals(Date.class)) {
            long dtval = new Date().getTime();
            if (value != null) {
                dtval = ((Date) value).getTime();
            }
            pstmnt.setLong(index, dtval);
        } else if (value instanceof Enum) {
            pstmnt.setString(index, getEnumValue(value));
        } else if (attr.Convertor != null) {
            pstmnt.setString(index, (String) attr.Convertor.save(entity, attr.Field.getName()));
        } else if (attr.Reference != null) {
            Class<?> cls = Class.forName(attr.Reference.Class);
            StructAttributeReflect rattr = ReflectionUtils.get().getAttribute(cls, attr.Reference.Field);
            Object refval = PropertyUtils.getSimpleProperty(entity, attr.Field.getName());
            value = PropertyUtils.getSimpleProperty(refval, rattr.Field.getName());
            setPreparedValue(pstmnt, index, rattr, value, entity);
        } else
            throw new Exception("Unsupported field type [" + type.getCanonicalName() + "]");
    }
}

From source file:com.kylinolap.rest.service.QueryService.java

/**
 * @param preparedState/*from  w ww  .  java 2s  .  c  o m*/
 * @param param
 * @throws SQLException
 */
private void setParam(PreparedStatement preparedState, int index, StateParam param) throws SQLException {
    boolean isNull = (null == param.getValue());

    Class<?> clazz = Object.class;
    try {
        clazz = Class.forName(param.getClassName());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Rep rep = Rep.of(clazz);

    switch (rep) {
    case PRIMITIVE_CHAR:
    case CHARACTER:
    case STRING:
        preparedState.setString(index, isNull ? null : String.valueOf(param.getValue()));
        break;
    case PRIMITIVE_INT:
    case INTEGER:
        preparedState.setInt(index, isNull ? null : Integer.valueOf(param.getValue()));
        break;
    case PRIMITIVE_SHORT:
    case SHORT:
        preparedState.setShort(index, isNull ? null : Short.valueOf(param.getValue()));
        break;
    case PRIMITIVE_LONG:
    case LONG:
        preparedState.setLong(index, isNull ? null : Long.valueOf(param.getValue()));
        break;
    case PRIMITIVE_FLOAT:
    case FLOAT:
        preparedState.setFloat(index, isNull ? null : Float.valueOf(param.getValue()));
        break;
    case PRIMITIVE_DOUBLE:
    case DOUBLE:
        preparedState.setDouble(index, isNull ? null : Double.valueOf(param.getValue()));
        break;
    case PRIMITIVE_BOOLEAN:
    case BOOLEAN:
        preparedState.setBoolean(index, isNull ? null : Boolean.parseBoolean(param.getValue()));
        break;
    case PRIMITIVE_BYTE:
    case BYTE:
        preparedState.setByte(index, isNull ? null : Byte.valueOf(param.getValue()));
        break;
    case JAVA_UTIL_DATE:
    case JAVA_SQL_DATE:
        preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIME:
        preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIMESTAMP:
        preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue()));
        break;
    default:
        preparedState.setObject(index, isNull ? null : param.getValue());
    }
}

From source file:br.com.cobranca.util.Util.java

public static <T> int inserirRegistro(T obj, Connection con) throws Exception {

    int id = 0;//from  w w  w.j a  v a  2 s .  co m

    String nomeTabela = obj.getClass().getSimpleName();

    String strSql = "INSERT INTO " + nomeTabela.toUpperCase() + " (";
    boolean usarVirgula = false;

    for (Field field : obj.getClass().getDeclaredFields()) {
        field.setAccessible(true);

        if (usarVirgula) {
            strSql = strSql + ", ";
        }

        strSql = strSql + field.getName();

        if (!usarVirgula) {
            usarVirgula = true;
        }
    }

    strSql = strSql + ") VALUES (";

    usarVirgula = false;

    for (Field field : obj.getClass().getDeclaredFields()) {
        field.setAccessible(true);

        if (usarVirgula) {
            strSql = strSql + ", ";
        }

        strSql = strSql + "?";

        if (!usarVirgula) {
            usarVirgula = true;
        }
    }

    strSql = strSql + ")";

    PreparedStatement ps = con.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS);

    try {

        int i = 1;
        for (Field field : obj.getClass().getDeclaredFields()) {

            String tipoColuna = field.getType().getSimpleName();

            if (tipoColuna.toUpperCase().contains("INT")) {
                tipoColuna = "Int";
            } else {
                tipoColuna = StringPrimeiraLetraMaiuscula(tipoColuna);
            }

            // obj . get + nome do campo
            Method met = obj.getClass().getMethod("get" + StringPrimeiraLetraMaiuscula(field.getName()));

            if (tipoColuna.equals("Int")) {

                Integer valor = (Integer) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setInt(i, valor);
                }

            } else if (tipoColuna.equals("String")) {
                String valor = (String) met.invoke(obj);
                ps.setString(i, valor);
            } else if (tipoColuna.equals("Double")) {

                Double valor = (Double) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setDouble(i, valor);
                }

            } else if (tipoColuna.equals("Float")) {

                Float valor = (Float) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setFloat(i, valor);
                }

            } else if (tipoColuna.equals("Long")) {

                Long valor = (Long) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setLong(i, valor);
                }

            } else if (tipoColuna.equals("Boolean")) {
                Boolean valor = (Boolean) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setBoolean(i, valor);
                }

            } else if (tipoColuna.equals("Date")) {
                Date valor = (Date) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setDate(i, new java.sql.Date(valor.getTime()));
                }

            } else {
                return 0;
            }

            i++;
        }

        int qtdLinhasAfetadas = ps.executeUpdate();

        if (qtdLinhasAfetadas > 0) {

            try (ResultSet rs = ps.getGeneratedKeys()) {
                if (rs.next()) {
                    id = rs.getInt(1);
                }
            }

        }
    } catch (Exception ex) {
        throw new Exception(ex.getMessage());
    } finally {
        ps.close();
    }

    return id;
}

From source file:org.dspace.storage.rdbms.MockDatabaseManager.java

/**
 * Iterate over the given parameters and add them to the given prepared statement.
 * Only a select number of datatypes are supported by the JDBC driver.
 *
 * @param statement/*w  ww  .ja  v  a 2  s  . co m*/
 *          The unparameterized statement.
 * @param parameters
 *          The parameters to be set on the statement.
 */
@Mock
protected static void loadParameters(PreparedStatement statement, Object[] parameters) throws SQLException {

    statement.clearParameters();

    for (int i = 0; i < parameters.length; i++) {
        // Select the object we are setting.
        Object parameter = parameters[i];
        int idx = i + 1; // JDBC starts counting at 1.

        if (parameter == null) {
            throw new SQLException("Attempting to insert null value into SQL query.");
        }
        if (parameter instanceof String) {
            statement.setString(idx, (String) parameters[i]);
        } else if (parameter instanceof Integer) {
            int ii = ((Integer) parameter).intValue();
            statement.setInt(idx, ii);
        } else if (parameter instanceof Double) {
            double d = ((Double) parameter).doubleValue();
            statement.setDouble(idx, d);
        } else if (parameter instanceof Float) {
            float f = ((Float) parameter).floatValue();
            statement.setFloat(idx, f);
        } else if (parameter instanceof Short) {
            short s = ((Short) parameter).shortValue();
            statement.setShort(idx, s);
        } else if (parameter instanceof Long) {
            long l = ((Long) parameter).longValue();
            statement.setLong(idx, l);
        } else if (parameter instanceof Date) {
            Date date = (Date) parameter;
            statement.setDate(idx, date);
        } else if (parameter instanceof Time) {
            Time time = (Time) parameter;
            statement.setTime(idx, time);
        } else if (parameter instanceof Timestamp) {
            Timestamp timestamp = (Timestamp) parameter;
            statement.setTimestamp(idx, timestamp);
        } else {
            throw new SQLException("Attempting to insert unknown datatype (" + parameter.getClass().getName()
                    + ") into SQL statement.");
        }
    }
}

From source file:lcn.module.batch.core.item.database.support.MethodMapItemPreparedStatementSetter.java

/**
 * params ? ? sqlType PreparedStatement? ??
 *///  www. j a  v  a 2 s. com
public void setValues(T item, PreparedStatement ps, String[] params, String[] sqlTypes,
        Map<String, Method> methodMap) throws SQLException {

    ReflectionSupport<T> reflector = new ReflectionSupport<T>();

    for (int i = 0; i < params.length; i++) {
        try {

            if (sqlTypes[i].equals("String")) {
                ps.setString(i + 1, (String) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("int")) {
                ps.setInt(i + 1, (Integer) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("double")) {
                ps.setDouble(i + 1, (Double) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Date")) {
                ps.setDate(i + 1, (Date) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte")) {
                ps.setByte(i + 1, (Byte) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("short")) {
                ps.setShort(i + 1, (Short) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("boolean")) {
                ps.setBoolean(i + 1, (Boolean) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("long")) {
                ps.setLong(i + 1, (Long) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Float")) {
                ps.setFloat(i + 1, (Float) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("BigDecimal")) {
                ps.setBigDecimal(i + 1, (BigDecimal) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte[]")) {
                ps.setBytes(i + 1, (byte[]) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else {
                throw new SQLException();
            }
        } catch (IllegalArgumentException e) {
            ReflectionUtils.handleReflectionException(e);
        }
    }
}