Example usage for java.sql PreparedStatement setDouble

List of usage examples for java.sql PreparedStatement setDouble

Introduction

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

Prototype

void setDouble(int parameterIndex, double x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java double value.

Usage

From source file:org.nuxeo.ecm.core.storage.sql.jdbc.dialect.DialectOracle.java

@Override
public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column)
        throws SQLException {
    switch (column.getJdbcType()) {
    case Types.VARCHAR:
    case Types.CLOB:
        setToPreparedStatementString(ps, index, value, column);
        return;/*w  ww  .  j a v a  2s. c o m*/
    case Types.BIT:
        ps.setBoolean(index, ((Boolean) value).booleanValue());
        return;
    case Types.TINYINT:
    case Types.SMALLINT:
        ps.setInt(index, ((Long) value).intValue());
        return;
    case Types.INTEGER:
    case Types.BIGINT:
        ps.setLong(index, ((Number) value).longValue());
        return;
    case Types.DOUBLE:
        ps.setDouble(index, ((Double) value).doubleValue());
        return;
    case Types.TIMESTAMP:
        setToPreparedStatementTimestamp(ps, index, value, column);
        return;
    case Types.OTHER:
        ColumnType type = column.getType();
        if (type.isId()) {
            setId(ps, index, value);
            return;
        } else if (type == ColumnType.FTSTORED) {
            ps.setString(index, (String) value);
            return;
        }
        throw new SQLException("Unhandled type: " + column.getType());
    default:
        throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
    }
}

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. j  a v a2 s . com*/

    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:net.pms.dlna.DLNAMediaDatabase.java

public synchronized void insertData(String name, long modified, int type, DLNAMediaInfo media) {
    Connection conn = null;/*  ww  w.  ja  v a 2s . c o  m*/
    PreparedStatement ps = null;
    try {
        conn = getConnection();
        ps = conn.prepareStatement(
                "INSERT INTO FILES(FILENAME, MODIFIED, TYPE, DURATION, BITRATE, WIDTH, HEIGHT, SIZE, CODECV, FRAMERATE, ASPECT, ASPECTRATIOCONTAINER, ASPECTRATIOVIDEOTRACK, REFRAMES, AVCLEVEL, BITSPERPIXEL, THUMB, CONTAINER, MODEL, EXPOSURE, ORIENTATION, ISO, MUXINGMODE, FRAMERATEMODE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        ps.setString(1, name);
        ps.setTimestamp(2, new Timestamp(modified));
        ps.setInt(3, type);
        if (media != null) {
            if (media.getDuration() != null) {
                ps.setDouble(4, media.getDurationInSeconds());
            } else {
                ps.setNull(4, Types.DOUBLE);
            }

            int databaseBitrate = 0;
            if (type != Format.IMAGE) {
                databaseBitrate = media.getBitrate();
                if (databaseBitrate == 0) {
                    logger.debug("Could not parse the bitrate from: " + name);
                }
            }
            ps.setInt(5, databaseBitrate);

            ps.setInt(6, media.getWidth());
            ps.setInt(7, media.getHeight());
            ps.setLong(8, media.getSize());
            ps.setString(9, left(media.getCodecV(), SIZE_CODECV));
            ps.setString(10, left(media.getFrameRate(), SIZE_FRAMERATE));
            ps.setString(11, left(media.getAspect(), SIZE_ASPECT));
            ps.setString(12, left(media.getAspect(), SIZE_ASPECTRATIO_CONTAINER));
            ps.setString(13, left(media.getAspect(), SIZE_ASPECTRATIO_VIDEOTRACK));
            ps.setByte(14, media.getReferenceFrameCount());
            ps.setString(15, left(media.getAvcLevel(), SIZE_AVC_LEVEL));
            ps.setInt(16, media.getBitsPerPixel());
            ps.setBytes(17, media.getThumb());
            ps.setString(18, left(media.getContainer(), SIZE_CONTAINER));
            if (media.getExtras() != null) {
                ps.setString(19, left(media.getExtrasAsString(), SIZE_MODEL));
            } else {
                ps.setString(19, left(media.getModel(), SIZE_MODEL));
            }
            ps.setInt(20, media.getExposure());
            ps.setInt(21, media.getOrientation());
            ps.setInt(22, media.getIso());
            ps.setString(23, left(media.getMuxingModeAudio(), SIZE_MUXINGMODE));
            ps.setString(24, left(media.getFrameRateMode(), SIZE_FRAMERATE_MODE));
        } else {
            ps.setString(4, null);
            ps.setInt(5, 0);
            ps.setInt(6, 0);
            ps.setInt(7, 0);
            ps.setLong(8, 0);
            ps.setString(9, null);
            ps.setString(10, null);
            ps.setString(11, null);
            ps.setString(12, null);
            ps.setString(13, null);
            ps.setByte(14, (byte) -1);
            ps.setString(15, null);
            ps.setInt(16, 0);
            ps.setBytes(17, null);
            ps.setString(18, null);
            ps.setString(19, null);
            ps.setInt(20, 0);
            ps.setInt(21, 0);
            ps.setInt(22, 0);
            ps.setString(23, null);
            ps.setString(24, null);
        }
        ps.executeUpdate();
        ResultSet rs = ps.getGeneratedKeys();
        int id = -1;
        while (rs.next()) {
            id = rs.getInt(1);
        }
        rs.close();
        if (media != null && id > -1) {
            PreparedStatement insert = null;
            if (media.getAudioTracksList().size() > 0) {
                insert = conn.prepareStatement(
                        "INSERT INTO AUDIOTRACKS VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            }

            for (DLNAMediaAudio audio : media.getAudioTracksList()) {
                insert.clearParameters();
                insert.setInt(1, id);
                insert.setInt(2, audio.getId());
                insert.setString(3, left(audio.getLang(), SIZE_LANG));
                insert.setString(4, left(audio.getFlavor(), SIZE_FLAVOR));
                insert.setInt(5, audio.getAudioProperties().getNumberOfChannels());
                insert.setString(6, left(audio.getSampleFrequency(), SIZE_SAMPLEFREQ));
                insert.setString(7, left(audio.getCodecA(), SIZE_CODECA));
                insert.setInt(8, audio.getBitsperSample());
                insert.setString(9, left(trimToEmpty(audio.getAlbum()), SIZE_ALBUM));
                insert.setString(10, left(trimToEmpty(audio.getArtist()), SIZE_ARTIST));
                insert.setString(11, left(trimToEmpty(audio.getSongname()), SIZE_SONGNAME));
                insert.setString(12, left(trimToEmpty(audio.getGenre()), SIZE_GENRE));
                insert.setInt(13, audio.getYear());
                insert.setInt(14, audio.getTrack());
                insert.setInt(15, audio.getAudioProperties().getAudioDelay());
                insert.setString(16, left(trimToEmpty(audio.getMuxingModeAudio()), SIZE_MUXINGMODE));
                insert.setInt(17, audio.getBitRate());

                try {
                    insert.executeUpdate();
                } catch (JdbcSQLException e) {
                    if (e.getErrorCode() == 23505) {
                        logger.debug(
                                "A duplicate key error occurred while trying to store the following file's audio information in the database: "
                                        + name);
                    } else {
                        logger.debug(
                                "An error occurred while trying to store the following file's audio information in the database: "
                                        + name);
                    }
                    logger.debug("The error given by jdbc was: " + e);
                }
            }

            if (media.getSubtitleTracksList().size() > 0) {
                insert = conn.prepareStatement("INSERT INTO SUBTRACKS VALUES (?, ?, ?, ?, ?)");
            }
            for (DLNAMediaSubtitle sub : media.getSubtitleTracksList()) {
                if (sub.getExternalFile() == null) { // no save of external subtitles
                    insert.clearParameters();
                    insert.setInt(1, id);
                    insert.setInt(2, sub.getId());
                    insert.setString(3, left(sub.getLang(), SIZE_LANG));
                    insert.setString(4, left(sub.getFlavor(), SIZE_FLAVOR));
                    insert.setInt(5, sub.getType().getStableIndex());
                    try {
                        insert.executeUpdate();
                    } catch (JdbcSQLException e) {
                        if (e.getErrorCode() == 23505) {
                            logger.debug(
                                    "A duplicate key error occurred while trying to store the following file's subtitle information in the database: "
                                            + name);
                        } else {
                            logger.debug(
                                    "An error occurred while trying to store the following file's subtitle information in the database: "
                                            + name);
                        }
                        logger.debug("The error given by jdbc was: " + e);
                    }
                }
            }
            close(insert);
        }
    } catch (SQLException se) {
        if (se.getErrorCode() == 23001) {
            logger.debug("Duplicate key while inserting this entry: " + name + " into the database: "
                    + se.getMessage());
        } else {
            logger.error(null, se);
        }
    } finally {
        close(ps);
        close(conn);
    }
}

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

public Order createOrder(String userID, String symbol, String orderType, double quantity, int holdingID)
        throws DAOException {
    int orderID = 0;
    Calendar minCalender = Calendar.getInstance();
    minCalender.setTimeInMillis(0);/* w  w  w . j  a v a  2 s . c om*/
    Order order = new Order(orderID, orderType, StockTraderUtility.ORDER_STATUS_OPEN, Calendar.getInstance(),
            minCalender, quantity, BigDecimal.valueOf(1), StockTraderUtility.getOrderFee(orderType), symbol);
    order.setHoldingId(holdingID);

    PreparedStatement getAccountId = null;
    try {
        getAccountId = sqlConnection.prepareStatement(SQL_GET_ACCOUNTID);
        getAccountId.setString(1, userID);
        ResultSet rs = getAccountId.executeQuery();
        if (rs.next()) {
            order.setAccountId(rs.getInt(1));
        }
    } catch (SQLException e) {
        throw new DAOException("", e);
    } finally {
        if (getAccountId != null) {
            try {
                getAccountId.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
    }

    PreparedStatement insertOrder = null;
    PreparedStatement selectOrderID = null;
    try {
        insertOrder = sqlConnection.prepareStatement(SQL_INSERT_ORDER);
        insertOrder.setBigDecimal(1, order.getOrderFee());
        insertOrder.setBigDecimal(2, order.getPrice());
        insertOrder.setString(3, order.getSymbol());
        // FIXED: metro used Double rather than double
        //         insertOrder.setFloat(4, (float) order.getQuantity());
        insertOrder.setFloat(4, order.getQuantity().floatValue());
        insertOrder.setString(5, order.getOrderType());
        insertOrder.setInt(6, order.getAccountId());
        insertOrder.setInt(7, order.getHoldingId());
        insertOrder.executeUpdate();

        selectOrderID = sqlConnection.prepareStatement(SQL_SELECT_ORDER_ID);
        // ORDERFEE = ? AND PRICE = ? AND QUOTE_SYMBOL = ? AND QUANTITY = ?
        // ORDERTYPE = ? ORDERSTATUS = ? AND ACCOUNT_ACCOUNTID = ?
        // HOLDING_HOLDINGID = ?"
        selectOrderID.setBigDecimal(1, order.getOrderFee());
        selectOrderID.setBigDecimal(2, order.getPrice());
        selectOrderID.setString(3, order.getSymbol());
        selectOrderID.setDouble(4, order.getQuantity());
        selectOrderID.setString(5, order.getOrderType());
        selectOrderID.setString(6, "open");
        selectOrderID.setInt(7, order.getAccountId());
        selectOrderID.setInt(8, order.getHoldingId());
        ResultSet rs = selectOrderID.executeQuery();
        if (rs.next()) {
            try {
                order.setOrderID(rs.getInt(1));
            } finally {
                try {
                    rs.close();
                } catch (SQLException e) {
                    logger.debug("", e);
                }
            }
        }
    } catch (SQLException e) {
        throw new DAOException("", e);
    } finally {
        if (insertOrder != null) {
            try {
                insertOrder.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
        if (selectOrderID != null) {
            try {
                selectOrderID.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
    }
    return order;
}

From source file:nl.tudelft.stocktrader.mysql.MySQLOrderDAO.java

public Order createOrder(String userID, String symbol, String orderType, double quantity, int holdingID)
        throws DAOException {
    int orderID = 0;
    Calendar minCalender = Calendar.getInstance();
    minCalender.setTimeInMillis(0);/*from   www .  j  a  va  2 s  .c  om*/
    Order order = new Order(orderID, orderType, StockTraderUtility.ORDER_STATUS_OPEN, Calendar.getInstance(),
            minCalender, quantity, BigDecimal.valueOf(1), StockTraderUtility.getOrderFee(orderType), symbol);
    order.setHoldingId(holdingID);

    PreparedStatement getAccountId = null;
    try {
        getAccountId = sqlConnection.prepareStatement(SQL_GET_ACCOUNTID);
        getAccountId.setString(1, userID);
        ResultSet rs = getAccountId.executeQuery();
        if (rs.next()) {
            order.setAccountId(rs.getInt(1));
        }
    } catch (SQLException e) {

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

    PreparedStatement insertOrder = null;
    PreparedStatement selectOrderID = null;
    try {
        insertOrder = sqlConnection.prepareStatement(SQL_INSERT_ORDER);
        insertOrder.setBigDecimal(1, order.getOrderFee());
        insertOrder.setBigDecimal(2, order.getPrice());
        insertOrder.setString(3, order.getSymbol());
        // FIXED: metro used Double rather than double
        //         insertOrder.setFloat(4, (float) order.getQuantity());
        insertOrder.setFloat(4, order.getQuantity().floatValue());
        insertOrder.setString(5, order.getOrderType());
        insertOrder.setInt(6, order.getAccountId());
        insertOrder.setInt(7, order.getHoldingId());
        insertOrder.executeUpdate();

        selectOrderID = sqlConnection.prepareStatement(SQL_SELECT_ORDER_ID);
        // ORDERFEE = ? AND PRICE = ? AND QUOTE_SYMBOL = ? AND QUANTITY = ?
        // ORDERTYPE = ? ORDERSTATUS = ? AND ACCOUNT_ACCOUNTID = ?
        // HOLDING_HOLDINGID = ?"
        selectOrderID.setBigDecimal(1, order.getOrderFee());
        selectOrderID.setBigDecimal(2, order.getPrice());
        selectOrderID.setString(3, order.getSymbol());
        selectOrderID.setDouble(4, order.getQuantity());
        selectOrderID.setString(5, order.getOrderType());
        selectOrderID.setString(6, "open");
        selectOrderID.setInt(7, order.getAccountId());
        selectOrderID.setInt(8, order.getHoldingId());
        ResultSet rs = selectOrderID.executeQuery();
        if (rs.next()) {
            try {
                order.setOrderID(rs.getInt(1));
            } finally {
                try {
                    rs.close();
                } catch (SQLException e) {
                    logger.debug("", e);
                }
            }
        }
    } catch (SQLException e) {
        throw new DAOException("", e);
    } finally {
        if (insertOrder != null) {
            try {
                insertOrder.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
        if (selectOrderID != null) {
            try {
                selectOrderID.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
    }
    return order;
}

From source file:mx.com.pixup.portal.dao.DiscoParserDaoJdbc.java

public void parserXML() {

    try {//from w w  w  .  jav a  2 s.  com

        //variables BD
        String sql = "INSERT INTO disco VALUES (?,?,?,?,?,?,?,?,?,?,?)";
        PreparedStatement preparedStatement;
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        //se obtiene elemento raiz
        Element discos = this.xmlDocument.getRootElement();
        //elementos 2do nivel
        List<Element> listaDiscos = discos.getChildren();
        Iterator<Element> i = listaDiscos.iterator();

        while (i.hasNext()) {
            Element disco = i.next();

            Attribute id = disco.getAttribute("id");
            Attribute idioma = disco.getAttribute("idioma");
            Attribute pais = disco.getAttribute("pais");
            Attribute disquera = disco.getAttribute("disquera");
            Attribute genero = disco.getAttribute("genero");

            //Elementos de 3er nivel
            Element titulo = disco.getChild("titulo");
            Element fechalanzamiento = disco.getChild("fechalanzamiento");
            Element precio = disco.getChild("precio");
            Element cantidad = disco.getChild("cantidad");
            Element promocion = disco.getChild("promocion");
            Element iva = disco.getChild("iva");

            //construye parametros de la query
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, id.getIntValue());
            preparedStatement.setString(2, titulo.getText());
            preparedStatement.setString(3, fechalanzamiento.getText());
            preparedStatement.setDouble(4, Double.parseDouble(precio.getText()));
            preparedStatement.setInt(5, Integer.parseInt(cantidad.getText()));
            preparedStatement.setInt(6, idioma.getIntValue());
            preparedStatement.setInt(7, pais.getIntValue());
            preparedStatement.setInt(8, disquera.getIntValue());
            preparedStatement.setInt(9, genero.getIntValue());
            preparedStatement.setInt(10, Integer.parseInt(promocion.getText()));
            preparedStatement.setInt(11, Integer.parseInt(iva.getText()));

            preparedStatement.execute();
        }

        connection.commit();
    } catch (Exception e) {
        //*** se quit el return porque el mtodo es void
        System.out.println(e.getMessage());
    }

}

From source file:org.dspace.storage.rdbms.DatabaseManager.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/* www.j  a  v a  2  s . c o m*/
 *          The unparameterized statement.
 * @param parameters
 *          The parameters to be set on the statement.
 */
protected static void loadParameters(PreparedStatement statement, Object[] parameters) throws SQLException {
    statement.clearParameters();

    int idx = 1;
    for (Object parameter : parameters) {
        if (parameter instanceof String) {
            statement.setString(idx, (String) parameter);
        } else if (parameter instanceof Long) {
            statement.setLong(idx, ((Long) parameter).longValue());
        } else if (parameter instanceof Integer) {
            statement.setInt(idx, ((Integer) parameter).intValue());
        } else if (parameter instanceof Short) {
            statement.setShort(idx, ((Short) parameter).shortValue());
        } else if (parameter instanceof Date) {
            statement.setDate(idx, (Date) parameter);
        } else if (parameter instanceof Time) {
            statement.setTime(idx, (Time) parameter);
        } else if (parameter instanceof Timestamp) {
            statement.setTimestamp(idx, (Timestamp) parameter);
        } else if (parameter instanceof Double) {
            statement.setDouble(idx, ((Double) parameter).doubleValue());
        } else if (parameter instanceof Float) {
            statement.setFloat(idx, ((Float) parameter).floatValue());
        } else if (parameter == null) {
            throw new SQLException("Attempting to insert null value into SQL query.");
        } else {
            throw new SQLException("Attempting to insert unknown datatype (" + parameter.getClass().getName()
                    + ") into SQL statement.");
        }

        idx++;
    }
}

From source file:com.wso2telco.dep.ratecardservice.dao.TariffDAO.java

public TariffDTO addTariff(TariffDTO tariff) throws BusinessException {

    Connection con = null;/* ww w .  java  2s. c o  m*/
    PreparedStatement ps = null;
    ResultSet rs = null;
    Integer tariffId = 0;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_RATE_DB);
        if (con == null) {

            log.error("unable to open " + DataSourceNames.WSO2TELCO_RATE_DB + " database connection");
            throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
        }

        StringBuilder query = new StringBuilder("insert into ");
        query.append(DatabaseTables.TARIFF.getTObject());
        query.append(
                " (tariffname, tariffdesc, tariffdefaultval, tariffmaxcount, tariffexcessrate, tariffdefrate, tariffspcommission, tariffadscommission, tariffopcocommission, tariffsurchargeval, tariffsurchargeAds, tariffsurchargeOpco, createdby)");
        query.append(" values");
        query.append(" (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        ps = con.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);

        log.debug("sql query in addTariff : " + ps);

        ps.setString(1, tariff.getTariffName());
        ps.setString(2, tariff.getTariffDescription());

        Double tariffDefaultVal = tariff.getTariffDefaultVal();
        if (tariffDefaultVal != null) {
            ps.setDouble(3, tariffDefaultVal);
        } else {
            ps.setNull(3, Types.DOUBLE);
        }

        Integer tariffMaxCount = tariff.getTariffMaxCount();
        if (tariffMaxCount != null) {
            ps.setInt(4, tariffMaxCount);
        } else {
            ps.setNull(4, Types.INTEGER);
        }

        Double tariffExcessRate = tariff.getTariffExcessRate();
        if (tariffExcessRate != null) {
            ps.setDouble(5, tariffExcessRate);
        } else {
            ps.setNull(5, Types.DOUBLE);
        }

        Double tariffDefRate = tariff.getTariffDefRate();
        if (tariffDefRate != null) {
            ps.setDouble(6, tariffDefRate);
        } else {
            ps.setNull(6, Types.DOUBLE);
        }

        Double tariffSPCommission = tariff.getTariffSPCommission();
        if (tariffSPCommission != null) {
            ps.setDouble(7, tariffSPCommission);
        } else {
            ps.setNull(7, Types.DOUBLE);
        }

        Double tariffAdsCommission = tariff.getTariffAdsCommission();
        if (tariffAdsCommission != null) {
            ps.setDouble(8, tariffAdsCommission);
        } else {
            ps.setNull(8, Types.DOUBLE);
        }

        Double tariffOpcoCommission = tariff.getTariffOpcoCommission();
        if (tariffOpcoCommission != null) {
            ps.setDouble(9, tariffOpcoCommission);
        } else {
            ps.setNull(9, Types.DOUBLE);
        }

        Double tariffSurChargeval = tariff.getTariffSurChargeval();
        if (tariffSurChargeval != null) {
            ps.setDouble(10, tariffSurChargeval);
        } else {
            ps.setNull(10, Types.DOUBLE);
        }

        Double tariffSurChargeAds = tariff.getTariffSurChargeAds();
        if (tariffSurChargeAds != null) {
            ps.setDouble(11, tariffSurChargeAds);
        } else {
            ps.setNull(11, Types.DOUBLE);
        }

        Double tariffSurChargeOpco = tariff.getTariffSurChargeOpco();
        if (tariffSurChargeOpco != null) {
            ps.setDouble(12, tariffSurChargeOpco);
        } else {
            ps.setNull(12, Types.DOUBLE);
        }

        ps.setString(13, tariff.getCreatedBy());

        ps.executeUpdate();

        rs = ps.getGeneratedKeys();

        while (rs.next()) {

            tariffId = rs.getInt(1);
        }

        tariff.setTariffId(tariffId);
    } catch (SQLException e) {

        log.error("database operation error in addTariff : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } catch (Exception e) {

        log.error("error in addTariff : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } finally {

        DbUtils.closeAllConnections(ps, con, rs);
    }

    return tariff;
}

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:/* w  w w. ja  va2 s.  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:gemlite.core.internal.db.AsyncEventHelper.java

/**
 * Set column value at given index in a prepared statement. The implementation
 * tries using the matching underlying type to minimize any data type
 * conversions, and avoid creating wrapper Java objects (e.g. {@link Integer}
 * for primitive int).//from   w w w .  ja  va 2s .co  m
 * 
 * @param type
 *          the SQL type of the column as specified by JDBC {@link Types}
 *          class
 * @param ps
 *          the prepared statement where the column value has to be set
 * @param row
 *          the source row as a {@link ResultSet} from where the value has to
 *          be extracted
 * @param rowPosition
 *          the 1-based position of the column in the provided
 *          <code>row</code>
 * @param paramIndex
 *          the 1-based position of the column in the target prepared
 *          statement (provided <code>ps</code> argument)
 * @param sync
 *          the {@link DBSynchronizer} object, if any; it is used to store
 *          whether the current driver is JDBC4 compliant to enable performing
 *          BLOB/CLOB operations {@link PreparedStatement#setBinaryStream},
 *          {@link PreparedStatement#setCharacterStream}
 * 
 * @throws SQLException
 *           in case of an exception in setting parameters
 */
public final void setColumnInPrepStatement(String type, Object val, PreparedStatement ps,
        final DBSynchronizer sync, int paramIndex) throws SQLException {
    switch (type) {
    case JavaTypes.STRING:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.VARCHAR);
        else {
            final String realVal = (String) val;
            ps.setString(paramIndex, realVal);
        }
        break;
    case JavaTypes.INT1:
    case JavaTypes.INT2:
    case JavaTypes.INT3:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.INTEGER);
        else {
            final int realVal = (int) val;
            ps.setInt(paramIndex, realVal);
        }
        break;
    case JavaTypes.DOUBLE1:
    case JavaTypes.DOUBLE2:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.DOUBLE);
        else {
            final double realVal = (double) val;
            ps.setDouble(paramIndex, realVal);
        }
        break;
    case JavaTypes.FLOAT1:
    case JavaTypes.FLOAT2:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.FLOAT);
        else {
            final float realVal = (float) val;
            ps.setDouble(paramIndex, realVal);
        }
        break;
    case JavaTypes.BOOLEAN1:
    case JavaTypes.BOOLEAN2:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.BOOLEAN);
        else {
            final boolean realVal = (boolean) val;
            ps.setBoolean(paramIndex, realVal);
        }
        break;
    case JavaTypes.DATE_SQL:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.DATE);
        else {
            final Date realVal = (Date) val;
            ps.setDate(paramIndex, realVal);
        }
        break;
    case JavaTypes.DATE_UTIL:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.DATE);
        else {
            final java.util.Date realVal = (java.util.Date) val;
            ps.setDate(paramIndex, new Date(realVal.getTime()));
        }
        break;
    case JavaTypes.BIGDECIMAL:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.DECIMAL);
        else {
            final BigDecimal realVal = (BigDecimal) val;
            ps.setBigDecimal(paramIndex, realVal);
        }
        break;
    case JavaTypes.TIME:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.TIME);
        else {
            final Time realVal = (Time) val;
            ps.setTime(paramIndex, realVal);
        }
        break;
    case JavaTypes.TIMESTAMP:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.TIMESTAMP);
        else {
            final Timestamp realVal = (Timestamp) val;
            ps.setTimestamp(paramIndex, realVal);
        }
        break;
    case JavaTypes.OBJECT:
        if (val == null || StringUtils.isEmpty(val.toString()))
            ps.setNull(paramIndex, Types.JAVA_OBJECT);
        else {
            final Object realVal = (Object) val;
            ps.setObject(paramIndex, realVal);
        }
        break;
    default:
        throw new UnsupportedOperationException("java.sql.Type = " + type + " not supported");
    }
}