Example usage for java.sql ResultSet getFloat

List of usage examples for java.sql ResultSet getFloat

Introduction

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

Prototype

float getFloat(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

From source file:se.technipelago.weather.chart.Generator.java

private HiLow getHighLow(Date from, Date to, String column, boolean max) {
    PreparedStatement stmt = null;
    ResultSet result = null;
    HiLow hilo = null;/*from   w w  w.ja  v a  2 s.  com*/
    String func = max ? "DESC" : "ASC";

    init();

    try {
        stmt = conn.prepareStatement("SELECT ts, " + column + " FROM archive WHERE ts BETWEEN ? AND ? ORDER BY "
                + column + " " + func + ", ts ASC");
        stmt.setTimestamp(1, new java.sql.Timestamp(from.getTime()));
        stmt.setTimestamp(2, new java.sql.Timestamp(to.getTime()));
        result = stmt.executeQuery();
        if (result.next()) {
            hilo = new HiLow(result.getTimestamp(1), result.getFloat(2));
        }
    } catch (SQLException ex) {
        Logger.getLogger(Generator.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException ex) {
                log.log(Level.WARNING, "Failed to close ResultSet", ex);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                log.log(Level.WARNING, "Failed to close select statement", ex);
            }
        }
    }
    return hilo;
}

From source file:org.dbist.dml.impl.DmlJdbc.java

private static Object toRequiredType(ResultSet rs, int index, Class<?> requiredType) throws SQLException {
    if (requiredType == null)
        return rs.getObject(index);
    if (ValueUtils.isPrimitive(requiredType)) {
        if (requiredType.equals(String.class))
            return rs.getString(index);
        if (requiredType.equals(Character.class) || requiredType.equals(char.class)) {
            String str = rs.getString(index);
            if (str == null || str.length() == 0)
                return null;
            return str.charAt(0);
        }/*ww  w  .j  a  v  a  2s  .  co m*/
        if (requiredType.equals(BigDecimal.class))
            return rs.getBigDecimal(index);
        if (requiredType.equals(Date.class))
            return rs.getTimestamp(index);
        if (requiredType.equals(Double.class) || requiredType.equals(double.class))
            return rs.getDouble(index);
        if (requiredType.equals(Float.class) || requiredType.equals(float.class))
            return rs.getFloat(index);
        if (requiredType.equals(Long.class) || requiredType.equals(long.class))
            return rs.getLong(index);
        if (requiredType.equals(Integer.class) || requiredType.equals(int.class))
            return rs.getInt(index);
        if (requiredType.equals(Boolean.class) || requiredType.equals(boolean.class))
            return rs.getBoolean(index);
        if (requiredType.equals(Byte[].class) || requiredType.equals(byte[].class))
            return rs.getBytes(index);
        if (requiredType.equals(Byte.class) || requiredType.equals(byte.class))
            return rs.getByte(index);
    }
    return rs.getObject(index);
}

From source file:ResultSetIterator.java

/**
 * Convert a <code>ResultSet</code> column into an object.  Simple 
 * implementations could just call <code>rs.getObject(index)</code> while
 * more complex implementations could perform type manipulation to match 
 * the column's type to the bean property type.
 * /* www .  j  a  va 2  s. c o  m*/
 * <p>
 * This implementation calls the appropriate <code>ResultSet</code> getter 
 * method for the given property type to perform the type conversion.  If 
 * the property type doesn't match one of the supported 
 * <code>ResultSet</code> types, <code>getObject</code> is called.
 * </p>
 * 
 * @param rs The <code>ResultSet</code> currently being processed.  It is
 * positioned on a valid row before being passed into this method.
 * 
 * @param index The current column index being processed.
 * 
 * @param propType The bean property type that this column needs to be
 * converted into.
 * 
 * @throws SQLException if a database access error occurs
 * 
 * @return The object from the <code>ResultSet</code> at the given column
 * index after optional type processing or <code>null</code> if the column
 * value was SQL NULL.
 */
protected Object processColumn(ResultSet rs, int index, Class propType) throws SQLException {

    if (!propType.isPrimitive() && rs.getObject(index) == null) {
        return null;
    }

    if (propType.equals(String.class)) {
        return rs.getString(index);

    } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
        return new Integer(rs.getInt(index));

    } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) {
        return new Boolean(rs.getBoolean(index));

    } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) {
        return new Long(rs.getLong(index));

    } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) {
        return new Double(rs.getDouble(index));

    } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) {
        return new Float(rs.getFloat(index));

    } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) {
        return new Short(rs.getShort(index));

    } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) {
        return new Byte(rs.getByte(index));

    } else if (propType.equals(Timestamp.class)) {
        return rs.getTimestamp(index);

    } else {
        return rs.getObject(index);
    }

}

From source file:br.com.blackhubos.eventozero.factory.Event.java

/**
 * Este mtodo ir restaurar um backup do jogador, salvo no banco de dados
 * do EventoZero com dados importantes sobre o jogador, tais como, vida,
 * comida, itens, xp, localizao, armadura, etc. Voc poder restaurar esse
 * backup ao jogador quando quiser, pois fica salvo em backup. Note que os
 * backups no so retirados do banco de dados aps restaurar, so apenas
 * 'trancados' e no podem mais ser usados.
 *
 * @param player// w  w w .j  ava2s. c  o  m
 */
public void playerRestore(final Player player) {
    if ((player == null) || ((player != null) && !player.isOnline()))
        throw new NullArgumentException("Player is null");
    final ResultSet rs = EventoZero.getStorage()
            .search("SELECT * FROM `" + Storage.Module.BACKUP.getTable() + "` WHERE `jogador`='"
                    + player.getName().toLowerCase() + "' AND `devolvido`='0' AND `evento`='"
                    + this.name.toLowerCase() + "';");
    try {
        if (rs.next()) {
            // TODO: isso  para ter compatibilidade de 1.5.2 (health por int) e 1.7+ (health por double)
            try {
                player.getClass().getMethod("setHealth", double.class).invoke(player,
                        (double) rs.getInt("vida"));
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException
                    | SecurityException e1) {
                try {
                    player.getClass().getMethod("setHealth", int.class).invoke(player, rs.getInt("vida"));
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException
                        | SecurityException e2) {
                }
            }
            player.setFoodLevel(rs.getInt("comida"));
            player.setExp(rs.getFloat("xp"));
            player.setLevel(rs.getInt("level"));
            player.teleport(Framework.toLocation(rs.getString("localizacao")));
            player.getInventory().setContents(
                    (ItemStack[]) this.getData().getData(player.getName() + ".inventory.contents"));
            player.getInventory().setArmorContents(
                    (ItemStack[]) this.getData().getData(player.getName() + ".inventory.armorContents"));
            this.getData().removeKeyStartWith(player.getName());
        }
    } catch (IllegalArgumentException | SQLException e) {
        e.printStackTrace();
    }

}

From source file:org.sakaiproject.webservices.SakaiReport.java

protected String toJsonString(ResultSet rs) throws SQLException, JSONException {
    ResultSetMetaData rsmd = rs.getMetaData();
    JSONArray array = new JSONArray();
    int numColumns = rsmd.getColumnCount();

    while (rs.next()) {

        JSONObject obj = new JSONObject();
        for (int i = 1; i < numColumns + 1; i++) {

            String column_label = rsmd.getColumnLabel(i);

            LOG.debug("Column Name=" + column_label + ",type=" + rsmd.getColumnType(i));

            switch (rsmd.getColumnType(i)) {
            case Types.ARRAY:
                obj.put(column_label, rs.getArray(i));
                break;
            case Types.BIGINT:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.BOOLEAN:
                obj.put(column_label, rs.getBoolean(i));
                break;
            case Types.BLOB:
                obj.put(column_label, rs.getBlob(i));
                break;
            case Types.DOUBLE:
                obj.put(column_label, rs.getDouble(i));
                break;
            case Types.FLOAT:
                obj.put(column_label, rs.getFloat(i));
                break;
            case Types.INTEGER:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.NVARCHAR:
                obj.put(column_label, rs.getNString(i));
                break;
            case Types.VARCHAR:
                obj.put(column_label, rs.getString(i));
                break;
            case Types.TINYINT:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.SMALLINT:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.DATE:
                obj.put(column_label, rs.getDate(i));
                break;
            case Types.TIMESTAMP:
                obj.put(column_label, rs.getTimestamp(i));
                break;
            default:
                obj.put(column_label, rs.getObject(i));
                break;
            }/*from  ww  w  .j a  v a  2s.co  m*/

        }
        array.put(obj);

    }
    return array.toString();
}

From source file:dsd.dao.ParametersDAO.java

public static List<Parameter> GetValidParameters(Calendar cal) {
    try {/*  ww w. ja va 2s .  com*/
        Connection con = DAOProvider.getDataSource().getConnection();
        ArrayList<Parameter> parametersList = new ArrayList<Parameter>();
        try {
            Object[] parameters = new Object[1];
            parameters[0] = new Timestamp(cal.getTimeInMillis());

            ResultSet results = DAOProvider.SelectTableSecure(
                    // table part
                    tableNameParameters + " join " + tableNameParameterData + " on " + tableNameParameters
                            + ".ID = " + tableNameParameterData + "." + tableParameterDataFields[0],
                    // select part
                    tableNameParameterData + "." + "ID" + " as " + tableNameParameterData + "_" + "ID" + ", "
                            + tableNameParameterData + "." + tableParameterDataFields[0] + " as "
                            + tableNameParameterData + "_" + tableParameterDataFields[0] + ", "
                            + tableNameParameterData + "." + tableParameterDataFields[1] + " as "
                            + tableNameParameterData + "_" + tableParameterDataFields[1] + ", "
                            + tableNameParameterData + "." + tableParameterDataFields[2] + " as "
                            + tableNameParameterData + "_" + tableParameterDataFields[2] + ", "
                            + tableNameParameterData + "." + tableParameterDataFields[3] + " as "
                            + tableNameParameterData + "_" + tableParameterDataFields[3] + ", "
                            + "parameters.* ",
                    // where part
                    " (parameters_id, timestamp) in (select parameters_id,  max(timestamp) "
                            + " from parameter_data " + " where timestamp < ? " + " group by parameters_id "
                            + "); ",
                    // order by part
                    "", con, parameters);
            while (results.next()) {
                Parameter parameter = new Parameter();
                parameter.setParameterID(results.getLong("ID"));
                parameter.setAbbreviation(results.getString(tableParametersFields[1]));
                parameter.setCategory(
                        eParameterCategory.getParameterCategory(results.getInt(tableParametersFields[4])));
                parameter.setName(results.getString(tableParametersFields[0]));
                parameter.setParameterDataID(results.getLong(tableNameParameterData + "_ID"));
                parameter.setTimestamp(results
                        .getTimestamp(tableNameParameterData + "_" + tableParameterDataFields[3]).getTime());
                parameter.setUnit(results.getString(tableParametersFields[2]));
                parameter.setUserID(results.getInt(tableNameParameterData + "_" + tableParameterDataFields[2]));
                parameter
                        .setValue(results.getFloat(tableNameParameterData + "_" + tableParameterDataFields[1]));
                parametersList.add(parameter);
            }
        } catch (Exception exc) {
            exc.printStackTrace();
        }
        con.close();
        return parametersList;
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    return null;
}

From source file:HW3.java

private void displayBusinessTable(ResultSet result) throws SQLException {
    TableColumnModel tableModel = jTable2.getColumnModel();
    tableModel.getColumn(0).setPreferredWidth(200);
    tableModel.getColumn(4).setPreferredWidth(200);
    DefaultTableModel model = (DefaultTableModel) jTable2.getModel();

    while (result.next()) {
        String bid = result.getString(1);
        String bname = result.getString(2);
        String bcity = result.getString(5);
        String bstate = result.getString(4);
        String bstars = result.getFloat(3) + "";
        String bzip = result.getString(6);
        model.addRow(new Object[] { bname, bcity, bstate, bstars, bid, bzip });
        //System.out.println(bid + "  " + bname + bcity + "  " + bstate + "  " + bstars);
    }/*from w ww  . jav a2 s .c om*/
    jTable2.repaint();
    if (jTable2.getRowCount() == 0) {
        JOptionPane.showMessageDialog(topPanel, "NO DATA TO DISPLAY", "Message",
                JOptionPane.INFORMATION_MESSAGE);
    }
}

From source file:org.geowebcache.storage.jdbc.jobstore.JDBCJobWrapper.java

private void readJob(JobObject job, ResultSet rs) throws SQLException {
    job.setJobId(rs.getLong("job_id"));
    job.setLayerName(rs.getString("layer_name"));
    job.setState(STATE.valueOf(rs.getString("state")));
    job.setTimeSpent(rs.getLong("time_spent"));
    job.setTimeRemaining(rs.getLong("time_remaining"));
    job.setTilesDone(rs.getLong("tiles_done"));
    job.setTilesTotal(rs.getLong("tiles_total"));
    job.setFailedTileCount(rs.getLong("failed_tile_count"));

    job.setBounds(new BoundingBox(rs.getString("bounds")));
    job.setGridSetId(rs.getString("gridset_id"));
    job.setSrs(SRS.getSRS(rs.getInt("srs")));

    job.setThreadCount(rs.getInt("thread_count"));
    job.setZoomStart(rs.getInt("zoom_start"));
    job.setZoomStop(rs.getInt("zoom_stop"));
    job.setFormat(rs.getString("format"));
    job.setJobType(TYPE.valueOf(rs.getString("job_type")));
    job.setThroughput(rs.getFloat("throughput"));
    job.setMaxThroughput(rs.getInt("max_throughput"));
    job.setPriority(PRIORITY.valueOf(rs.getString("priority")));
    job.setSchedule(rs.getString("schedule"));
    job.setRunOnce(rs.getBoolean("run_once"));
    job.setSpawnedBy(rs.getLong("spawned_by"));
    job.setFilterUpdate(rs.getBoolean("filter_update"));
    job.setEncodedParameters(rs.getString("parameters"));

    job.setTimeFirstStart(rs.getTimestamp("time_first_start"));
    job.setTimeLatestStart(rs.getTimestamp("time_latest_start"));
    job.setTimeFinish(rs.getTimestamp("time_finish"));
}

From source file:csiro.pidsvc.mappingstore.ManagerJson.java

@SuppressWarnings("unchecked")
public JSONObject getLookups(int page, String namespace) throws SQLException {
    PreparedStatement pst = null;
    ResultSet rs = null;
    JSONObject ret = new JSONObject();
    final int pageSize = 20;

    try {/*  w  w w  .  jav a2s.co  m*/
        String query = "";
        if (namespace != null && !namespace.isEmpty())
            query += " AND ns ILIKE ?";

        query = "SELECT COUNT(*) FROM lookup_ns" + (query.isEmpty() ? "" : " WHERE " + query.substring(5))
                + ";\n" + "SELECT * FROM lookup_ns" + (query.isEmpty() ? "" : " WHERE " + query.substring(5))
                + " ORDER BY ns LIMIT " + pageSize + " OFFSET " + ((page - 1) * pageSize) + ";";

        pst = _connection.prepareStatement(query);
        for (int i = 1, j = 0; j < 2; ++j) {
            // Bind parameters twice to two almost identical queries.
            if (namespace != null && !namespace.isEmpty())
                pst.setString(i++, "%" + namespace.replace("\\", "\\\\") + "%");
        }

        if (pst.execute()) {
            rs = pst.getResultSet();
            rs.next();
            ret.put("count", rs.getInt(1));
            ret.put("page", page);
            ret.put("pages", (int) Math.ceil(rs.getFloat(1) / pageSize));

            JSONArray jsonArr = new JSONArray();
            for (pst.getMoreResults(), rs = pst.getResultSet(); rs.next();) {
                jsonArr.add(JSONObjectHelper.create("ns", rs.getString("ns"), "type", rs.getString("type")));
            }
            ret.put("results", jsonArr);
        }
    } finally {
        if (rs != null)
            rs.close();
        if (pst != null)
            pst.close();
    }
    return ret;
}

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

/**
 * Gets a vulnerability for the provided CVE.
 *
 * @param cve the CVE to lookup/*from www  . j a  va 2  s.co  m*/
 * @return a vulnerability object
 * @throws DatabaseException if an exception occurs
 */
public synchronized Vulnerability getVulnerability(String cve) throws DatabaseException {
    ResultSet rsV = null;
    ResultSet rsR = null;
    ResultSet rsS = null;
    Vulnerability vuln = null;

    try {
        final PreparedStatement psV = getPreparedStatement(SELECT_VULNERABILITY);
        psV.setString(1, cve);
        rsV = psV.executeQuery();
        if (rsV.next()) {
            vuln = new Vulnerability();
            vuln.setName(cve);
            vuln.setDescription(rsV.getString(2));
            String cwe = rsV.getString(3);
            if (cwe != null) {
                final String name = CweDB.getCweName(cwe);
                if (name != null) {
                    cwe += ' ' + name;
                }
            }
            final int cveId = rsV.getInt(1);
            vuln.setCwe(cwe);
            vuln.setCvssScore(rsV.getFloat(4));
            vuln.setCvssAccessVector(rsV.getString(5));
            vuln.setCvssAccessComplexity(rsV.getString(6));
            vuln.setCvssAuthentication(rsV.getString(7));
            vuln.setCvssConfidentialityImpact(rsV.getString(8));
            vuln.setCvssIntegrityImpact(rsV.getString(9));
            vuln.setCvssAvailabilityImpact(rsV.getString(10));

            final PreparedStatement psR = getPreparedStatement(SELECT_REFERENCES);
            psR.setInt(1, cveId);
            rsR = psR.executeQuery();
            while (rsR.next()) {
                vuln.addReference(rsR.getString(1), rsR.getString(2), rsR.getString(3));
            }

            final PreparedStatement psS = getPreparedStatement(SELECT_SOFTWARE);
            psS.setInt(1, cveId);
            rsS = psS.executeQuery();
            while (rsS.next()) {
                final String cpe = rsS.getString(1);
                final String prevVersion = rsS.getString(2);
                if (prevVersion == null) {
                    vuln.addVulnerableSoftware(cpe);
                } else {
                    vuln.addVulnerableSoftware(cpe, prevVersion);
                }
            }
        }
    } catch (SQLException ex) {
        throw new DatabaseException("Error retrieving " + cve, ex);
    } finally {
        DBUtils.closeResultSet(rsV);
        DBUtils.closeResultSet(rsR);
        DBUtils.closeResultSet(rsS);
    }
    return vuln;
}