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:dk.netarkivet.harvester.datamodel.RunningJobsInfoDBDAO.java

/**
 * Get a list of StartedJobInfo objects from a resultset of entries 
 * from runningJobsHistory table./*w w  w .j  a v a 2 s .c o m*/
 * @param rs a resultset with entries from table runningJobsHistory.
 * @return a list of StartedJobInfo objects from the resultset
 * @throws SQLException If any problems reading data from the resultset
 */
private List<StartedJobInfo> listFromResultSet(ResultSet rs) throws SQLException {
    List<StartedJobInfo> list = new LinkedList<StartedJobInfo>();
    while (rs.next()) {
        StartedJobInfo sji = new StartedJobInfo(rs.getString(HM_COLUMN.harvestName.rank()),
                rs.getLong(HM_COLUMN.jobId.rank()));
        sji.setElapsedSeconds(rs.getLong(HM_COLUMN.elapsedSeconds.rank()));
        sji.setHostUrl(rs.getString(HM_COLUMN.hostUrl.rank()));
        sji.setProgress(rs.getDouble(HM_COLUMN.progress.rank()));
        sji.setQueuedFilesCount(rs.getLong(HM_COLUMN.queuedFilesCount.rank()));
        sji.setTotalQueuesCount(rs.getLong(HM_COLUMN.totalQueuesCount.rank()));
        sji.setActiveQueuesCount(rs.getLong(HM_COLUMN.activeQueuesCount.rank()));
        sji.setExhaustedQueuesCount(rs.getLong(HM_COLUMN.exhaustedQueuesCount.rank()));
        sji.setAlertsCount(rs.getLong(HM_COLUMN.alertsCount.rank()));
        sji.setDownloadedFilesCount(rs.getLong(HM_COLUMN.downloadedFilesCount.rank()));
        sji.setCurrentProcessedKBPerSec(rs.getLong(HM_COLUMN.currentProcessedKBPerSec.rank()));
        sji.setProcessedKBPerSec(rs.getLong(HM_COLUMN.processedKBPerSec.rank()));
        sji.setCurrentProcessedDocsPerSec(rs.getDouble(HM_COLUMN.currentProcessedDocsPerSec.rank()));
        sji.setProcessedDocsPerSec(rs.getDouble(HM_COLUMN.processedDocsPerSec.rank()));
        sji.setActiveToeCount(rs.getInt(HM_COLUMN.activeToeCount.rank()));
        sji.setStatus(CrawlStatus.values()[rs.getInt(HM_COLUMN.status.rank())]);
        sji.setTimestamp(new Date(rs.getTimestamp(HM_COLUMN.tstamp.rank()).getTime()));

        list.add(sji);
    }
    return list;
}

From source file:chh.utils.db.source.common.JdbcClient.java

public List<List<Column>> select(String sqlQuery, List<Column> queryParams) {
    Connection connection = null;
    try {// w  ww  .  j a v  a 2 s . c om
        connection = connectionProvider.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
        if (queryTimeoutSecs > 0) {
            preparedStatement.setQueryTimeout(queryTimeoutSecs);
        }
        setPreparedStatementParams(preparedStatement, queryParams);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<List<Column>> rows = Lists.newArrayList();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<Column> row = Lists.newArrayList();
            for (int i = 1; i <= columnCount; i++) {
                String columnLabel = metaData.getColumnLabel(i);
                int columnType = metaData.getColumnType(i);
                Class columnJavaType = Util.getJavaType(columnType);
                if (columnJavaType.equals(String.class)) {
                    row.add(new Column<String>(columnLabel, resultSet.getString(columnLabel), columnType));
                } else if (columnJavaType.equals(Integer.class)) {
                    row.add(new Column<Integer>(columnLabel, resultSet.getInt(columnLabel), columnType));
                } else if (columnJavaType.equals(Double.class)) {
                    row.add(new Column<Double>(columnLabel, resultSet.getDouble(columnLabel), columnType));
                } else if (columnJavaType.equals(Float.class)) {
                    row.add(new Column<Float>(columnLabel, resultSet.getFloat(columnLabel), columnType));
                } else if (columnJavaType.equals(Short.class)) {
                    row.add(new Column<Short>(columnLabel, resultSet.getShort(columnLabel), columnType));
                } else if (columnJavaType.equals(Boolean.class)) {
                    row.add(new Column<Boolean>(columnLabel, resultSet.getBoolean(columnLabel), columnType));
                } else if (columnJavaType.equals(byte[].class)) {
                    row.add(new Column<byte[]>(columnLabel, resultSet.getBytes(columnLabel), columnType));
                } else if (columnJavaType.equals(Long.class)) {
                    row.add(new Column<Long>(columnLabel, resultSet.getLong(columnLabel), columnType));
                } else if (columnJavaType.equals(Date.class)) {
                    row.add(new Column<Date>(columnLabel, resultSet.getDate(columnLabel), columnType));
                } else if (columnJavaType.equals(Time.class)) {
                    row.add(new Column<Time>(columnLabel, resultSet.getTime(columnLabel), columnType));
                } else if (columnJavaType.equals(Timestamp.class)) {
                    row.add(new Column<Timestamp>(columnLabel, resultSet.getTimestamp(columnLabel),
                            columnType));
                } else {
                    throw new RuntimeException(
                            "type =  " + columnType + " for column " + columnLabel + " not supported.");
                }
            }
            rows.add(row);
        }
        return rows;
    } catch (SQLException e) {
        throw new RuntimeException("Failed to execute select query " + sqlQuery, e);
    } finally {
        closeConnection(connection);
    }
}

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

/**
 * This method is used to get active games for which Direct player PWT can
 * be received./*  w w  w  .  j a v a  2 s.c  o  m*/
 * 
 * @return List of active games
 * @throws LMSException
 */
public List getActiveGames() throws LMSException {

    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    String delimiter = new String("-");

    try {

        ActiveGameBean gameBean = null;
        List<ActiveGameBean> searchResults = new ArrayList<ActiveGameBean>();

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

        String query = QueryManager.getST1ActiveGamesQuery();
        resultSet = statement.executeQuery(query);
        int gameNbr;
        String gameName;

        while (resultSet.next()) {

            gameBean = new ActiveGameBean();
            gameBean.setGameId(resultSet.getInt(TableConstants.SGM_GAME_ID));
            gameBean.setPlayerPwtCommRate(resultSet.getDouble(TableConstants.SGM_AGT_PWT_RATE));
            gameNbr = resultSet.getInt(TableConstants.SGM_GAME_NBR);
            gameName = resultSet.getString(TableConstants.SGM_GAME_NAME);
            gameBean.setGameNbr_Name(gameNbr + delimiter + gameName);

            searchResults.add(gameBean);

        }

        return searchResults;

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

        try {

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

}

From source file:com.intellectualcrafters.plot.database.SQLManager.java

@Override
public double getRatings(final Plot plot) {
    try {/* w  w  w .j  a  v  a  2s.  co m*/
        final PreparedStatement statement = connection.prepareStatement(
                "SELECT AVG(`rating`) AS `rating` FROM `" + prefix + "plot_ratings` WHERE `plot_plot_id` = ? ");
        statement.setInt(1, getId(plot.getWorld().getName(), plot.id));
        final ResultSet set = statement.executeQuery();
        double rating = 0;
        while (set.next()) {
            rating = set.getDouble("rating");
        }
        statement.close();
        return rating;
    } catch (final SQLException e) {
        Logger.add(LogLevel.WARNING, "Failed to fetch rating for plot " + plot.getId().toString());
        e.printStackTrace();
    }
    return 0.0d;
}

From source file:org.efs.openreports.engine.ChartReportEngine.java

/**
 * Executes the Chart query and builds an array of ChartValues from the results.
 *//*  w w w .ja v a  2  s  .com*/
public ChartValue[] getChartValues(ReportChart reportChart, Map parameters) throws ProviderException {
    Connection conn = null;
    PreparedStatement pStmt = null;
    ResultSet rs = null;

    try {
        ReportDataSource dataSource = reportChart.getDataSource();
        conn = dataSourceProvider.getConnection(dataSource.getId());

        // Use JasperReports Query logic to parse parameters in chart
        // queries

        JRDesignQuery query = new JRDesignQuery();
        query.setText(reportChart.getQuery());

        // convert parameters to JRDesignParameters so they can be parsed
        Map jrParameters = ORUtil.buildJRDesignParameters(parameters);

        pStmt = JRQueryExecuter.getStatement(query, jrParameters, parameters, conn);

        rs = pStmt.executeQuery();

        Vector v = new Vector();

        int chartType = reportChart.getChartType();
        if (chartType == ReportChart.BAR_CHART) {
            while (rs.next()) {
                CategoryChartValue catValue = new CategoryChartValue();

                catValue.setValue(rs.getDouble(1));
                catValue.setSeries(rs.getString(2));
                catValue.setCategory(rs.getString(3));

                v.add(catValue);
            }
        } else if (chartType == ReportChart.PIE_CHART || chartType == ReportChart.RING_CHART) {
            while (rs.next()) {
                PieChartValue pieValue = new PieChartValue();

                pieValue.setValue(rs.getDouble(1));
                pieValue.setKey(rs.getString(2));

                v.add(pieValue);
            }
        } else if (chartType == ReportChart.XY_CHART) {
            while (rs.next()) {
                XYChartValue xyValue = new XYChartValue();

                xyValue.setSeries(rs.getString(1));
                xyValue.setValue(rs.getDouble(2));
                xyValue.setSecondValue(rs.getDouble(3));

                v.add(xyValue);
            }
        } else if (chartType == ReportChart.TIME_CHART) {
            while (rs.next()) {
                TimeChartValue timeValue = new TimeChartValue();

                timeValue.setSeries(rs.getString(1));
                timeValue.setValue(rs.getDouble(2));
                timeValue.setTime(rs.getTimestamp(3));

                v.add(timeValue);
            }
        }

        ChartValue[] values = new ChartValue[v.size()];
        v.copyInto(values);

        return values;
    } catch (Exception e) {
        e.printStackTrace();
        throw new ProviderException(
                LocalStrings.getString(LocalStrings.ERROR_CHARTQUERY_INVALID) + ": " + e.toString());
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (pStmt != null)
                pStmt.close();
            if (conn != null)
                conn.close();
        } catch (Exception c) {
            log.error("Error closing");
        }
    }
}

From source file:com.itemanalysis.jmetrik.graph.nicc.NonparametricCurveAnalysis.java

private void initializeGridPoints() throws SQLException {
    Statement stmt = null;//from   w  w w .  ja  va 2  s. c  o m
    ResultSet rs = null;

    //connect to db
    try {
        Table sqlTable = new Table(tableName.getNameForDatabase());
        SelectQuery select = new SelectQuery();
        select.addColumn(sqlTable, regressorVariable.getName().nameForDatabase());
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery(select.toString());

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

        double value = 0.0;
        while (rs.next()) {
            value = rs.getDouble(regressorVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                min.increment(value);
                max.increment(value);
                mean.increment(value);
                sd.increment(value);
            }
            updateProgress();
        }
        rs.close();
        stmt.close();

        //evaluation points
        double sdv = sd.getResult();
        double mn = mean.getResult();
        double lower = mn - 2.5 * sdv;
        double upper = mn + 2.5 * sdv;
        bwAdjustment *= sdv;
        bandwidth = new NonparametricIccBandwidth(sampleSize, bwAdjustment);
        gridPoints = command.getFreeOption("gridpoints").getInteger();
        //            uniformDistributionApproximation = new UniformDistributionApproximation(
        //                    min.getResult(), max.getResult(), gridPoints);
        uniformDistributionApproximation = new UniformDistributionApproximation(lower, upper, gridPoints);

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

}

From source file:dk.netarkivet.harvester.datamodel.RunningJobsInfoDBDAO.java

/**
 * Returns the most recent progress record for the given job ID.
 * @param jobId the job id.//from  w  ww  . jav a2  s.c  o  m
 * @return the most recent progress record for the given job ID.
 */
@Override
public StartedJobInfo getMostRecentByJobId(long jobId) {
    Connection c = HarvestDBConnection.get();
    Statement stm = null;
    try {
        stm = c.createStatement();
        ResultSet rs = stm.executeQuery("SELECT " + HM_COLUMN.getColumnsInOrder() + " FROM runningJobsMonitor"
                + " WHERE jobId=" + jobId);

        if (rs.next()) {
            String harvestName = rs.getString(HM_COLUMN.harvestName.rank());
            StartedJobInfo sji = new StartedJobInfo(harvestName, jobId);

            sji.setElapsedSeconds(rs.getLong(HM_COLUMN.elapsedSeconds.rank()));
            sji.setHostUrl(rs.getString(HM_COLUMN.hostUrl.rank()));
            sji.setProgress(rs.getDouble(HM_COLUMN.progress.rank()));
            sji.setQueuedFilesCount(rs.getLong(HM_COLUMN.queuedFilesCount.rank()));
            sji.setTotalQueuesCount(rs.getLong(HM_COLUMN.totalQueuesCount.rank()));
            sji.setActiveQueuesCount(rs.getLong(HM_COLUMN.activeQueuesCount.rank()));
            sji.setRetiredQueuesCount(rs.getLong(HM_COLUMN.retiredQueuesCount.rank()));
            sji.setExhaustedQueuesCount(rs.getLong(HM_COLUMN.exhaustedQueuesCount.rank()));
            sji.setAlertsCount(rs.getLong(HM_COLUMN.alertsCount.rank()));
            sji.setDownloadedFilesCount(rs.getLong(HM_COLUMN.downloadedFilesCount.rank()));
            sji.setCurrentProcessedKBPerSec(rs.getLong(HM_COLUMN.currentProcessedKBPerSec.rank()));
            sji.setProcessedKBPerSec(rs.getLong(HM_COLUMN.processedKBPerSec.rank()));
            sji.setCurrentProcessedDocsPerSec(rs.getDouble(HM_COLUMN.currentProcessedDocsPerSec.rank()));
            sji.setProcessedDocsPerSec(rs.getDouble(HM_COLUMN.processedDocsPerSec.rank()));
            sji.setActiveToeCount(rs.getInt(HM_COLUMN.activeToeCount.rank()));
            sji.setStatus(CrawlStatus.values()[rs.getInt(HM_COLUMN.status.rank())]);
            sji.setTimestamp(new Date(rs.getTimestamp(HM_COLUMN.tstamp.rank()).getTime()));

            return sji;
        }

    } catch (SQLException e) {
        String message = "SQL error querying runningJobsMonitor" + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new IOFailure(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(stm);
        HarvestDBConnection.release(c);
    }

    throw new UnknownID("No running job with ID " + jobId);
}

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

public List<EnergyTimestep> getApplianceEnergyConsumptionForMonitor(EnergyMonitor energyMonitor,
        int algorithmId, Date start, Date end) {
    final List<UserAppliance> userAppliances = getUserAppliancesForAlgorithmForEnergyMonitor(energyMonitor,
            algorithmId);/*w  w w.j  a  va2  s .  co  m*/

    List<EnergyTimestep> energyTimesteps = jdbcTemplate.query(
            "select p.* from appliance_energy_consumption_predictions p, user_appliances a, energy_monitors m where p.detection_algorithm = ? and m.user_id = ? and m.monitor_type = ? and m.monitor_id = ? and m.id = a.energy_monitor_id and a.id = p.user_appliance_id and p.start_time >= ? and p.end_time < ? order by p.start_time",
            new Object[] { algorithmId, energyMonitor.getUserId(), energyMonitor.getType(),
                    energyMonitor.getMonitorId(), start.getTime(), end.getTime() },
            new RowMapper<EnergyTimestep>() {

                public EnergyTimestep mapRow(ResultSet rs, int arg1) throws SQLException {
                    EnergyTimestep energyTimestep = new EnergyTimestep();

                    long startTime = rs.getLong("start_time");
                    long endTime = rs.getLong("end_time");
                    energyTimestep.setStartTime(new Date(startTime));
                    energyTimestep.setEndTime(new Date(endTime));
                    energyTimestep.setEnergyConsumed(rs.getDouble("energy_consumed"));

                    int userApplianceId = rs.getInt("user_appliance_id");

                    for (UserAppliance app : userAppliances) {
                        if (app.getId() == userApplianceId) {
                            energyTimestep.setUserAppliance(app);
                        }
                    }

                    return energyTimestep;
                }
            });

    return energyTimesteps;
}

From source file:com.clustercontrol.sql.factory.RunMonitorSql.java

/**
 * SQL?/*  w  ww  .j a  v a 2 s. co m*/
 * 
 * @param facilityId ID
 * @return ???????true
 */
@Override
public boolean collect(String facilityId) {
    // set Generation Date
    if (m_now != null) {
        m_nodeDate = m_now.getTime();
    }

    boolean result = false;

    AccessDB access = null;
    ResultSet rSet = null;

    String url = m_url;

    try {
        // ???URL??
        if (nodeInfo != null && nodeInfo.containsKey(facilityId)) {
            Map<String, String> nodeParameter = RepositoryUtil.createNodeParameter(nodeInfo.get(facilityId));
            StringBinder strbinder = new StringBinder(nodeParameter);
            url = strbinder.bindParam(m_url);
            if (m_log.isTraceEnabled())
                m_log.trace("jdbc request. (nodeInfo = " + nodeInfo + ", facilityId = " + facilityId
                        + ", url = " + url + ")");
        }

        // DB??
        access = new AccessDB(m_jdbcDriver, url, m_user, m_password);

        // SQL?????
        if (m_query.length() >= 6) {
            String work = m_query.substring(0, 6);
            if (work.equalsIgnoreCase("SELECT")) {
                rSet = access.read(m_query);

                //1?1??
                rSet.first();
                double count = rSet.getDouble(1);
                m_value = count;

                //?
                rSet.last();
                int number = rSet.getRow();

                NumberFormat numberFormat = NumberFormat.getNumberInstance();
                m_message = MessageConstant.SELECT_VALUE.getMessage() + " : " + m_value;
                m_messageOrg = MessageConstant.RECORD_VALUE.getMessage() + " : " + numberFormat.format(m_value)
                        + ", " + MessageConstant.RECORDS_NUMBER.getMessage() + " : "
                        + numberFormat.format(number);
                m_messageOrg += "\n" + MessageConstant.CONNECTION_URL.getMessage() + " : " + url;

                result = true;
            } else {
                //SELECT?
                m_log.info("collect(): "
                        + MessageConstant.MESSAGE_PLEASE_SET_SELECT_STATEMENT_IN_SQL.getMessage());
                m_unKnownMessage = MessageConstant.MESSAGE_PLEASE_SET_SELECT_STATEMENT_IN_SQL.getMessage();
                m_messageOrg = MessageConstant.SQL_STRING.getMessage() + " : " + m_query;
                m_messageOrg += "\n" + MessageConstant.CONNECTION_URL.getMessage() + " : " + url;
            }
        } else {
            //SELECT?
            m_log.info("collect(): " + MessageConstant.MESSAGE_PLEASE_SET_SELECT_STATEMENT_IN_SQL.getMessage());
            m_unKnownMessage = MessageConstant.MESSAGE_PLEASE_SET_SELECT_STATEMENT_IN_SQL.getMessage();
            m_messageOrg = MessageConstant.SQL_STRING.getMessage() + " : " + m_query;
            m_messageOrg += "\n" + MessageConstant.CONNECTION_URL.getMessage() + " : " + url;
        }
    } catch (ClassNotFoundException e) {
        m_log.debug("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        m_unKnownMessage = MessageConstant.MESSAGE_CANNOT_FIND_JDBC_DRIVER.getMessage();
        m_messageOrg = MessageConstant.SQL_STRING.getMessage() + " : " + m_query + " (" + e.getMessage() + ")";
        m_messageOrg += "\n" + MessageConstant.CONNECTION_URL.getMessage() + " : " + url;
    } catch (SQLException e) {
        // SQL
        m_log.info("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        m_unKnownMessage = MessageConstant.MESSAGE_FAILED_TO_EXECUTE_SQL.getMessage();
        m_messageOrg = MessageConstant.SQL_STRING.getMessage() + " : " + m_query + " (" + e.getMessage() + ")";
        m_messageOrg += "\n" + MessageConstant.CONNECTION_URL.getMessage() + " : " + url;
    } finally {
        try {
            if (rSet != null) {
                rSet.close();
            }
            if (access != null) {
                // DB?
                access.terminate();
            }
        } catch (SQLException e) {
            m_log.warn("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
        }
    }
    return result;
}

From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.excel.DBExcelUtility.java

private ArrayList getRowData(ResultSet rs, String colnames[], String coltype[]) throws Exception {
    ArrayList data = new ArrayList();
    int numberOfColumns = coltype.length;
    short col = 0;
    boolean nodata = true;

    for (int i = 0; i < numberOfColumns; i++) {
        String dat = "";

        if (coltype[i].equalsIgnoreCase(DataType.TYPE_STRING)) {
            String cdata = rs.getString(colnames[i]);

            data.add(cdata);//from  w w w.  j a va 2 s  . c o m
        } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_INTEGER)) {
            Integer idata = new Integer(rs.getInt(colnames[i]));

            data.add(idata);
        } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_DOUBLE)) {
            Double ddata = new Double(rs.getDouble(colnames[i]));

            data.add(ddata);
        } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_BOOLEAN)) {
            Boolean bdata = new Boolean(rs.getBoolean(colnames[i]));

            data.add(bdata);
        } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_DATE)) {
            Date dtval = rs.getDate(colnames[i]);

            data.add(dtval);
        }
    }
    return data;
}