Example usage for java.sql ResultSet getDouble

List of usage examples for java.sql ResultSet getDouble

Introduction

In this page you can find the example usage for java.sql ResultSet getDouble.

Prototype

double getDouble(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language.

Usage

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

public List<Order> getCompletedOrders(String userId) throws DAOException {
    PreparedStatement selectClosedOrders = null;
    PreparedStatement updateClosedOrders = null;
    try {//  ww  w . j a v a 2  s . c om
        selectClosedOrders = sqlConnection.prepareStatement(SQL_SELECT_CLOSED_ORDERS);
        selectClosedOrders.setString(1, userId);
        ResultSet rs = selectClosedOrders.executeQuery();
        List<Order> closedOrders = new ArrayList<Order>();

        try {
            while (rs.next()) {
                int orderId = rs.getInt(1);
                Calendar openDate = StockTraderUtility.convertToCalendar(rs.getDate(4));
                Calendar completionDate = null;
                try {
                    completionDate = StockTraderUtility.convertToCalendar(rs.getDate(5));
                } catch (SQLException e) {
                    logger.debug("", e);
                    completionDate = Calendar.getInstance();
                    completionDate.setTimeInMillis(0);
                }
                Order closedOrderBean = new Order(orderId, rs.getString(2), rs.getString(3), openDate,
                        completionDate, rs.getDouble(6), rs.getBigDecimal(7), rs.getBigDecimal(8),
                        rs.getString(9));
                closedOrderBean.setOrderStatus(StockTraderUtility.ORDER_STATUS_CLOSED);
                closedOrders.add(closedOrderBean);
            }
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }

        if (!closedOrders.isEmpty()) {
            updateClosedOrders = sqlConnection.prepareStatement(SQL_UPDATE_CLOSED_ORDERS);
            updateClosedOrders.setString(1, userId);
            updateClosedOrders.executeUpdate();
        }

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

    }
}

From source file:com.cws.esolutions.core.dao.impl.ApplicationDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IApplicationDataDAO#getApplication(java.lang.String)
 *//*from www . j  a va 2 s  .  c o m*/
public synchronized List<Object> getApplication(final String value) throws SQLException {
    final String methodName = IApplicationDataDAO.CNAME
            + "#getApplication(final String value) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("value: {}", value);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object> responseData = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL getApplicationData(?)}");
        stmt.setString(1, value);

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("resultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.first();

                responseData = new ArrayList<Object>(Arrays.asList(resultSet.getString(1), // APPLICATION_GUID
                        resultSet.getString(2), // APPLICATION_NAME
                        resultSet.getDouble(3), // APPLICATION_VERSION
                        resultSet.getString(4), // INSTALLATION_PATH
                        resultSet.getString(5), // PACKAGE_LOCATION
                        resultSet.getString(6), // PACKAGE_INSTALLER
                        resultSet.getString(7), // INSTALLER_OPTIONS
                        resultSet.getString(8), // LOGS_DIRECTORY
                        resultSet.getString(9) // PLATFORM_GUID
                ));

                if (DEBUG) {
                    DEBUGGER.debug("data: {}", responseData);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return responseData;
}

From source file:com.itemanalysis.jmetrik.stats.transformation.LinearTransformationAnalysis.java

public String transformScore() throws SQLException {
    Statement stmt = null;//from   ww  w. j  av a 2  s . c  om
    ResultSet rs = null;
    Double constrainedScore = null;

    try {
        //add variable to db
        dao.addColumnToDb(conn, tableName, addedVariableInfo);

        conn.setAutoCommit(false);//begin transaction

        Table sqlTable = new Table(tableName.getNameForDatabase());
        SelectQuery select = new SelectQuery();
        select.addColumn(sqlTable, selectedVariable.getName().nameForDatabase());
        select.addColumn(sqlTable, addedVariableInfo.getName().nameForDatabase());
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        rs = stmt.executeQuery(select.toString());

        this.firePropertyChange("message", "", "Transforming scores...");

        double origValue = 0.0;
        double transValue = 0.0;
        double z = 0.0;

        StandardDeviation sd = new StandardDeviation();
        Mean mean = new Mean();
        Min min = new Min();
        Max max = new Max();

        while (rs.next()) {
            origValue = rs.getDouble(selectedVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                sd.increment(origValue);
                mean.increment(origValue);
                min.increment(origValue);
                max.increment(origValue);
            }
            updateProgress();
        }

        double meanValue = mean.getResult();
        double sdValue = sd.getResult();
        double minValue = min.getResult();
        double maxValue = max.getResult();
        double A = 1.0;
        double B = 0.0;

        rs.beforeFirst();

        while (rs.next()) {
            origValue = rs.getDouble(selectedVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                if (type1) {
                    z = (origValue - meanValue) / sdValue;
                    transValue = scaleSd * z + scaleMean;
                    transValue = checkConstraints(transValue);
                } else {
                    A = (maxPossibleScore - minPossibleScore) / (maxValue - minValue);
                    B = minPossibleScore - minValue * A;
                    transValue = origValue * A + B;
                    transValue = checkConstraints(transValue);
                }

                descriptiveStatistics.increment(transValue);

                rs.updateDouble(addedVariableInfo.getName().nameForDatabase(), transValue);
                rs.updateRow();
            }
            updateProgress();
        }

        conn.commit();
        conn.setAutoCommit(true);

        //create output
        DefaultLinearTransformation linearTransformation = new DefaultLinearTransformation();
        linearTransformation.setScale(A);
        linearTransformation.setIntercept(B);

        StringBuilder sb = new StringBuilder();
        Formatter f = new Formatter(sb);
        f.format(publishHeader());
        f.format(descriptiveStatistics.toString());
        f.format(linearTransformation.toString());
        f.format("%n");
        f.format("%n");
        return f.toString();

    } catch (SQLException ex) {
        conn.rollback();
        conn.setAutoCommit(true);
        throw ex;
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
    }

}

From source file:com.skilrock.lms.coreEngine.accMgmt.common.SearchChequeHelper.java

/**
 * This method is used to search cheque which submitted by the retailer
 * //from  w w  w  .  j  a  v a  2  s  . c  o  m
 * @param searchMap
 * @return
 * @throws LMSException
 */
public List searchChequeRetailer(Map searchMap, int agent_id, double chequeBounceCharge) throws LMSException {

    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    logger.debug("-----Query----::");
    try {

        ChequeBean chequeBean = null;
        List<ChequeBean> searchResults = new ArrayList<ChequeBean>();

        connection = DBConnect.getConnection();
        statement = connection.createStatement();

        String dynamicWhereClause = getWhereClauseForRetailer(searchMap);
        String query = QueryManager.getST5ChequeSearchRetailerQuery() + "and agent_user_id=" + agent_id + ""
                + dynamicWhereClause;

        logger.debug("-----Query----::" + query);

        resultSet = statement.executeQuery(query);

        while (resultSet.next()) {

            chequeBean = new ChequeBean();
            logger.debug("-----Query----::");

            chequeBean.setChequeNumber(resultSet.getString("cheque_nbr"));

            chequeBean.setChequeDate(resultSet.getDate(TableConstants.CHEQUE_DATE).toString());
            chequeBean.setIssuePartyname(resultSet.getString(TableConstants.ISSUE_PARTY_NAME));
            chequeBean.setBankName(resultSet.getString(TableConstants.DRAWEE_BANK));
            chequeBean.setChequeAmount(resultSet.getDouble(TableConstants.CHEQUE_AMT));
            chequeBean.setOrgName(resultSet.getString(TableConstants.NAME));
            chequeBean.setTransactionId(resultSet.getLong(TableConstants.TRANSACTION_ID));
            // chequeBean.setChequeBounceCharges(chequeBounceCharge);

            searchResults.add(chequeBean);

            logger.debug("Cheque Number" + resultSet.getString("cheque_nbr"));
            logger.debug("Org Name:" + resultSet.getString(TableConstants.NAME));
            logger.debug("Bank" + resultSet.getString(TableConstants.DRAWEE_BANK));

        }
        return searchResults;
    }

    catch (SQLException e) {
        logger.error("Exception: " + e);
        e.printStackTrace();
        throw new LMSException(e);
    } finally {

        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException se) {
            logger.error("Exception: " + se);
            throw new LMSException(se);
        }
    }

}

From source file:com.itemanalysis.jmetrik.stats.frequency.FrequencyAnalysis.java

public void summarize() throws SQLException {
    Statement stmt = null;//  w  w  w .  ja va  2s  . co m
    ResultSet rs = null;

    frequencyTables = new LinkedHashMap<VariableAttributes, Frequency>();
    Frequency temp = null;

    Table sqlTable = new Table(tableName.getNameForDatabase());
    SelectQuery select = new SelectQuery();
    for (VariableAttributes v : variables) {
        select.addColumn(sqlTable, v.getName().nameForDatabase());
    }
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery(select.toString());

    String strValue = "";
    double dblValue = 0;
    while (rs.next()) {
        for (VariableAttributes v : variables) {
            temp = frequencyTables.get(v);
            if (temp == null) {
                temp = new Frequency();
                frequencyTables.put(v, temp);
            }
            if (v.getType().getDataType() == DataType.STRING) {
                strValue = rs.getString(v.getName().nameForDatabase());
                if (!rs.wasNull() && !"".equals(strValue)) {
                    temp.addValue(strValue);
                }
            } else {
                dblValue = rs.getDouble(v.getName().nameForDatabase());
                if (!rs.wasNull()) {
                    temp.addValue(dblValue);
                }
            }
        }
        updateProgress();
    }
    rs.close();
    stmt.close();

    for (VariableAttributes v : frequencyTables.keySet()) {
        publishTable(v);
    }

}

From source file:com.flexive.core.storage.genericSQL.GenericBinarySQLStorage.java

/**
 * {@inheritDoc}/*from  ww w . j  a  v  a2  s  .c  o  m*/
 */
@Override
public BinaryDescriptor loadBinaryDescriptor(List<ServerLocation> server, Connection con, long id)
        throws FxDbException {
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement(BINARY_DESC_LOAD);
        ps.setLong(1, id);
        ps.setInt(2, 1); //ver
        ps.setInt(3, 1); //ver
        ResultSet rs = ps.executeQuery();
        if (rs != null && rs.next()) {
            return new BinaryDescriptor(server, id, 1, 1, rs.getLong(3), rs.getString(1), rs.getLong(2), null,
                    rs.getString(4), rs.getBoolean(5), rs.getDouble(6), rs.getInt(7), rs.getInt(8),
                    rs.getString(9));
        }
    } catch (SQLException e) {
        throw new FxDbException(e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(GenericBinarySQLStorage.class, ps);
    }
    throw new FxDbException("ex.content.binary.loadDescriptor.failed", id);
}

From source file:org.meerkat.services.WebApp.java

/**
 * getLatencyAverage/*ww w.  j  a  v  a2 s .c o  m*/
 * 
 * @return Latency average
 */
public final double getLatencyAverage() {
    double latencyAvg = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(
                "SELECT AVG(LATENCY) FROM MEERKAT.EVENTS WHERE APPNAME LIKE '" + this.name + "'");
        rs = ps.executeQuery();

        rs.next();
        latencyAvg = rs.getDouble(1);

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average load time from application " + this.getName());
        log.error("", e);
    }

    return latencyAvg;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getLatencyAverage/*from w w  w  . j  a  v  a2s . com*/
 * 
 * @return Latency average
 */
private final double getAvailabilityAverage() {
    double availAvg = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(
                "SELECT AVG(AVAILABILITY) FROM MEERKAT.EVENTS WHERE APPNAME LIKE '" + this.name + "'");
        rs = ps.executeQuery();

        rs.next();
        availAvg = rs.getDouble(1);

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd = new BigDecimal(availAvg);
    bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
    availAvg = bd.doubleValue();

    return availAvg;
}

From source file:org.obiba.onyx.jade.instrument.gehealthcare.AchillesExpressInstrumentRunner.java

@SuppressWarnings("unchecked")
private List<Map<String, Data>> retrieveDeviceData() {

    log.info("retrieveDeviceData");

    return (List<Map<String, Data>>) achillesExpressDb.query(
            "select assessment, fxrisk, total, tscore, zscore, agematched, percentnormal, sidescanned, stiffnessindex, patients.chart_num, results.SOS, results.BUA, achillesbitmap, appversion, roi_x, roi_y, roi_s, patients.Chart_Num, patients.FName, patients.LName, patients.Sex, patients.DOB from results, patients where results.chart_num = patients.chart_num and patients.chart_num = ?",
            new PreparedStatementSetter() {

                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setString(1, participantID);
                }/*from  ww  w .j  a  v  a 2s  . c o  m*/

            },

            new ResultSetExtractor() {

                public Object extractData(ResultSet rs) throws SQLException {

                    List<Map<String, Data>> boneDensityDataList = new ArrayList<Map<String, Data>>();

                    while (rs.next()) {
                        Map<String, Data> boneDensityData = new HashMap<String, Data>();

                        boneDensityData.put("OUTPUT_PARTICIPANT_BARCODE",
                                DataBuilder.buildText(rs.getString("Chart_Num")));
                        boneDensityData.put("OUTPUT_PARTICIPANT_FIRST_NAME",
                                DataBuilder.buildText(rs.getString("FName")));
                        boneDensityData.put("OUTPUT_PARTICIPANT_LAST_NAME",
                                DataBuilder.buildText(rs.getString("LName")));
                        boneDensityData.put("OUTPUT_PARTICIPANT_DATE_BIRTH",
                                DataBuilder.buildDate(rs.getDate("DOB")));

                        String gender = rs.getString("Sex").equals("M") ? "MALE" : "FEMALE";
                        boneDensityData.put("OUTPUT_PARTICIPANT_GENDER", DataBuilder.buildText(gender));

                        boneDensityData.put("RES_ASSESSMENT",
                                DataBuilder.buildDecimal(rs.getDouble("assessment")));
                        boneDensityData.put("RES_FRACTURE_RISK",
                                DataBuilder.buildDecimal(rs.getDouble("fxrisk")));
                        boneDensityData.put("RES_STIFFNESS_INDEX_RES",
                                DataBuilder.buildDecimal(rs.getDouble("total")));
                        boneDensityData.put("RES_T-SCORE", DataBuilder.buildDecimal(rs.getDouble("tscore")));
                        boneDensityData.put("RES_Z-SCORE", DataBuilder.buildDecimal(rs.getDouble("zscore")));
                        boneDensityData.put("RES_PERCENT_AGE_MATCHED",
                                DataBuilder.buildDecimal(rs.getDouble("agematched")));
                        boneDensityData.put("RES_PERCENT_YOUNG_ADULT",
                                DataBuilder.buildDecimal(rs.getDouble("percentnormal")));

                        String foot_scanned = rs.getString("sidescanned").equals("L") ? "LEFT_FOOT"
                                : "RIGHT_FOOT";
                        boneDensityData.put("OUTPUT_FOOT_SCANNED", DataBuilder.buildText(foot_scanned));

                        boneDensityData.put("RES_STIFFNESS_INDEX",
                                DataBuilder.buildDecimal(rs.getDouble("stiffnessindex")));
                        boneDensityData.put("RES_SPEED_ULTRASOUND",
                                DataBuilder.buildDecimal(rs.getDouble("SOS")));
                        boneDensityData.put("RES_BROADBAND_ULTRASOUND_ATT",
                                DataBuilder.buildDecimal(rs.getDouble("BUA")));
                        boneDensityData.put("RES_SOFTWARE_VERSION",
                                DataBuilder.buildText(rs.getString("appversion")));
                        boneDensityData.put("RES_REGION_INTERSECTION_X_COOR",
                                DataBuilder.buildInteger(rs.getLong("roi_x")));
                        boneDensityData.put("RES_REGION_INTERSECTION_Y_COOR",
                                DataBuilder.buildInteger(rs.getLong("roi_y")));
                        boneDensityData.put("RES_REGION_INTERSECTION_Z_COOR",
                                DataBuilder.buildInteger(rs.getLong("roi_s")));
                        boneDensityData.put("RES_STIFFNESS_INDEX_GRAPH",
                                DataBuilder.buildBinary(rs.getBinaryStream("achillesbitmap")));

                        boneDensityDataList.add(boneDensityData);
                    }

                    return boneDensityDataList;

                }

            });

}

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

public List<TariffDTO> getTariffs() throws BusinessException {

    List<TariffDTO> tariffs = new ArrayList<TariffDTO>();

    Connection con = null;//from  w w w .  j  a va  2  s .c om
    ResultSet rs = null;
    PreparedStatement ps = null;

    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(
                "select tariffid, tariffname, tariffdesc, tariffdefaultval, tariffmaxcount, tariffexcessrate, tariffdefrate, tariffspcommission, tariffadscommission, tariffopcocommission, tariffsurchargeval, tariffsurchargeAds, tariffsurchargeOpco, createdby from ");
        query.append(DatabaseTables.TARIFF.getTObject());

        ps = con.prepareStatement(query.toString());

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

        rs = ps.executeQuery();

        while (rs.next()) {

            TariffDTO tariff = new TariffDTO();

            tariff.setTariffId(rs.getInt("tariffid"));
            tariff.setTariffName(rs.getString("tariffname"));
            tariff.setTariffDescription(rs.getString("tariffdesc"));
            tariff.setTariffDefaultVal(rs.getDouble("tariffdefaultval"));
            tariff.setTariffMaxCount(rs.getInt("tariffmaxcount"));
            tariff.setTariffExcessRate(rs.getDouble("tariffexcessrate"));
            tariff.setTariffDefRate(rs.getDouble("tariffdefrate"));
            tariff.setTariffSPCommission(rs.getDouble("tariffspcommission"));
            tariff.setTariffAdsCommission(rs.getDouble("tariffadscommission"));
            tariff.setTariffOpcoCommission(rs.getDouble("tariffopcocommission"));
            tariff.setTariffSurChargeval(rs.getDouble("tariffsurchargeval"));
            tariff.setTariffSurChargeAds(rs.getDouble("tariffsurchargeAds"));
            tariff.setTariffSurChargeOpco(rs.getDouble("tariffsurchargeOpco"));
            tariff.setCreatedBy(rs.getString("createdby"));

            tariffs.add(tariff);
        }
    } catch (SQLException e) {

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

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

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

    return tariffs;
}