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:org.trafodion.rest.util.JdbcT4Util.java

public static JSONArray convertResultSetToJSON(java.sql.ResultSet rs) throws Exception {
    if (LOG.isDebugEnabled())
        LOG.debug("Begin convertResultSetToJSON");

    JSONArray json = new JSONArray();

    try {//w  w  w. j  ava 2 s.c  o  m

        java.sql.ResultSetMetaData rsmd = rs.getMetaData();

        while (rs.next()) {
            int numColumns = rsmd.getColumnCount();
            JSONObject obj = new JSONObject();

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

                String column_name = rsmd.getColumnName(i);

                if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                    obj.put(column_name, rs.getArray(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                    obj.put(column_name, rs.getLong(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                    obj.put(column_name, rs.getBoolean(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                    obj.put(column_name, rs.getBlob(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                    obj.put(column_name, rs.getDouble(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                    obj.put(column_name, rs.getFloat(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                    obj.put(column_name, rs.getInt(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                    obj.put(column_name, rs.getNString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.CHAR
                        || rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                    //prevent obj.put from removing null key value from JSONObject
                    String s = rs.getString(column_name);
                    if (s == null)
                        obj.put(column_name, new String(""));
                    else
                        obj.put(column_name, rs.getString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                    obj.put(column_name, rs.getInt(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                    obj.put(column_name, rs.getInt(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                    obj.put(column_name, rs.getDate(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                    obj.put(column_name, rs.getTimestamp(column_name));
                } else {
                    obj.put(column_name, rs.getObject(column_name));
                }

            } //end foreach 
            json.put(obj);

        } //end while 

        if (json.length() == 0) {

            int numColumns = rsmd.getColumnCount();
            JSONObject obj = new JSONObject();

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

                String column_name = rsmd.getColumnName(i);
                obj.put(column_name, "");
            }
            json.put(obj);
        }

    } catch (SQLException e) {
        e.printStackTrace();
        if (LOG.isDebugEnabled())
            LOG.error(e.getMessage());
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        if (LOG.isDebugEnabled())
            LOG.error(e.getMessage());
        throw e;
    }

    if (LOG.isDebugEnabled())
        LOG.debug("End convertResultSetToJSON");

    return json;
}

From source file:security.MySecurityRealm.java

/**
 * Authenticate a user./*from ww w  .j  a v a  2s .co  m*/
 *
 * @param username a username
 * @param password a plain text password, as entered by the user
 * @return true if the username/password combination is valid, false otherwise
 */
public boolean booleanAuthenticate(String username, String password) {
    boolean autenticado = false;
    String pass = HashAlgorithm.SHA256(password, username);

    if (Constantes.DB.equals("hsqldb")) {
        try {
            String url = Connection.URL_BASE;
            String usuarioAux = Connection.connect(url + "user/" + username + "/" + pass);
            JSONArray usuario = new JSONArray(usuarioAux);

            if (usuario.length() == 1) {
                autenticado = true;
                String tipoUsuario = usuario.getJSONObject(0).getString("user_type");
                String latitud = usuario.getJSONObject(0).getString("latitud");
                String longitud = usuario.getJSONObject(0).getString("longitud");
                String descripcion = usuario.getJSONObject(0).getString("real_name");
                String informacion = usuario.getJSONObject(0).getString("email");
                String planta = usuario.getJSONObject(0).getString("planta");
                Connection.connect(url + "insertar/" + tipoUsuario + "/" + username + "/" + descripcion + "/"
                        + informacion + "/" + latitud + "/" + longitud + "/" + planta);
            }
        } catch (JSONException ex) {
            System.out.println("JSONExcepcion: " + ex);
        }
    } else {
        try {
            Class.forName(Constantes.DB_DRIVER);
            java.sql.Connection conexion = DriverManager.getConnection(Constantes.DB_URL, Constantes.DB_USER,
                    Constantes.DB_PASS);
            Statement s = conexion.createStatement();
            ResultSet rs = s.executeQuery(SQLQueries.user(username, pass));
            if (rs.next()) {
                autenticado = true;
                String date = new java.sql.Timestamp(new Date().getTime()).toString();
                String tipoUsuario = rs.getString(2);
                String descripcion = rs.getString(3);
                String informacion = rs.getString(4);
                float latitud = rs.getFloat(5);
                float longitud = rs.getFloat(6);
                int planta = rs.getInt(7);

                ResultSet rs2 = s.executeQuery(SQLQueries.preInsertar(username));
                int estado = 1;
                if (rs2.next()) {
                    int id2 = rs2.getInt(1);
                    estado = rs2.getInt(2);
                    s.executeUpdate(SQLQueries.postPreInsertar(date, id2));
                }
                s.executeUpdate(SQLQueries.insertar(tipoUsuario, username, descripcion, informacion, latitud,
                        longitud, estado, date, planta));
            }
            conexion.close();
        } catch (ClassNotFoundException ex) {
            System.out.println("ClassNotFoundExcepcion: " + ex);
        } catch (SQLException ex) {
            System.out.println("SQLExcepcion: " + ex);
        }
    }
    return autenticado;
}

From source file:org.etudes.jforum.dao.generic.GenericGradeDAO.java

/**
 * @param rs - result set//from  w w w.j  a v  a2 s  .  c  om
 * @return Grade - grade
 */
protected Grade fillGrade(ResultSet rs) throws Exception {
    Grade grade = new Grade();

    grade.setId(rs.getInt("grade_id"));
    grade.setContext(rs.getString("context"));
    grade.setType(rs.getInt("grade_type"));
    grade.setForumId(rs.getInt("forum_id"));
    grade.setTopicId(rs.getInt("topic_id"));
    grade.setCategoryId(rs.getInt("categories_id"));
    grade.setPoints(rs.getFloat("points"));
    if (rs.getInt("add_to_gradebook") == 1)
        grade.setAddToGradeBook(true);
    else
        grade.setAddToGradeBook(false);

    if (rs.getInt("min_posts_required") == 1) {
        grade.setMinimumPostsRequired(true);
        grade.setMinimumPosts(rs.getInt("min_posts"));
    } else {
        grade.setMinimumPostsRequired(false);
        grade.setMinimumPosts(rs.getInt("min_posts"));
    }

    return grade;
}

From source file:com.l2jfree.gameserver.model.entity.faction.Faction.java

public Faction(int factionId) {
    _Id = factionId;/*w w  w .  j a v a 2  s . c o  m*/
    String _classlist = "";
    String _npclist = "";
    String _titlelist = "";
    int _tside = 0;

    Connection con = null;
    try {
        PreparedStatement statement;
        ResultSet rs;

        con = L2DatabaseFactory.getInstance().getConnection(con);

        statement = con.prepareStatement("Select * from factions where id = ?");
        statement.setInt(1, getId());
        rs = statement.executeQuery();

        while (rs.next()) {
            _name = rs.getString("name");
            _joinprice = rs.getInt("price");
            _classlist = rs.getString("allowed_classes");
            _titlelist = rs.getString("titlelist");
            _npclist = rs.getString("npcs");
            _points = rs.getFloat("points");
            _tside = rs.getInt("side");
        }
        statement.close();

        if (_tside <= 2)
            _side = _tside;

        if (_classlist.length() > 0)
            for (String id : _classlist.split(","))
                _list_classes.add(Integer.parseInt(id));

        if (_npclist.length() > 0)
            for (String id : _npclist.split(","))
                _list_npcs.add(Integer.parseInt(id));

        if (_titlelist.length() > 0)
            for (String id : _titlelist.split(";"))
                _list_title.put(Integer.valueOf(id.split(",")[0]), id.split(",")[1]);
    } catch (Exception e) {
        _log.warn("Exception: Faction load: " + e.getMessage(), e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:org.apache.phoenix.hive.HivePhoenixStoreIT.java

/**
 * Datatype Test/*from   ww  w  .  j  a v  a2s . com*/
 *
 * @throws Exception
 */
@Test
public void MultiKey() throws Exception {
    String testName = "MultiKey";
    // create a dummy outfile under log folder
    hbaseTestUtil.getTestFileSystem().createNewFile(new Path(hiveLogDir, testName + ".out"));
    createFile(StringUtil.EMPTY_STRING, new Path(hiveLogDir, testName + ".out").toString());
    createFile(StringUtil.EMPTY_STRING, new Path(hiveOutputDir, testName + ".out").toString());
    StringBuilder sb = new StringBuilder();
    sb.append("CREATE TABLE phoenix_MultiKey(ID int, ID2 String,description STRING, ts "
            + "TIMESTAMP, db DOUBLE,fl FLOAT, us INT)" + HiveTestUtil.CRLF
            + " STORED BY  \"org.apache.phoenix.hive.PhoenixStorageHandler\"" + HiveTestUtil.CRLF
            + " TBLPROPERTIES(" + HiveTestUtil.CRLF + "   'phoenix.hbase.table.name'='phoenix_MultiKey',"
            + HiveTestUtil.CRLF + "   'phoenix.zookeeper.znode.parent'='hbase'," + HiveTestUtil.CRLF
            + "   'phoenix.zookeeper.quorum'='localhost:" + hbaseTestUtil.getZkCluster().getClientPort() + "',"
            + HiveTestUtil.CRLF + "   'phoenix.rowkeys'='id,id2');");
    sb.append("INSERT INTO TABLE phoenix_MultiKey" + HiveTestUtil.CRLF
            + "VALUES (10,  \"part2\",\"foodesc\",\"2013-01-05 01:01:01\",200,2.0,-1);" + HiveTestUtil.CRLF);
    String fullPath = new Path(hbaseTestUtil.getDataTestDir(), testName).toString();
    createFile(sb.toString(), fullPath);
    runTest(testName, fullPath);

    String phoenixQuery = "SELECT * FROM phoenix_MultiKey";
    PreparedStatement statement = conn.prepareStatement(phoenixQuery);
    ResultSet rs = statement.executeQuery();
    assert (rs.getMetaData().getColumnCount() == 7);
    while (rs.next()) {
        assert (rs.getInt(1) == 10);
        assert (rs.getString(2).equalsIgnoreCase("part2"));
        assert (rs.getString(3).equalsIgnoreCase("foodesc"));
        //assert(rs.getTimestamp(4).equals(Timestamp.valueOf("2013-01-05 02:01:01")));
        assert (rs.getDouble(5) == 200);
        assert (rs.getFloat(6) == 2.0);
        assert (rs.getInt(7) == -1);
    }
}

From source file:API.Distributions.java

JSONArray getDistributions() {

    /* produce json */

    JSONArray json = new JSONArray();
    try {/*  w  w  w . ja va 2 s. c o m*/
        String sql = "";
        PreparedStatement s = con.prepareStatement(sql);
        if (type == 0) {
            sql = ("SELECT * from distributions;");
            s = con.prepareStatement(sql);
        } else if (type == 1) {
            sql = ("SELECT * from distributions where type = 'request' and to_location_id = ?;");
            s = con.prepareStatement(sql);
            s.setInt(1, location_id);
        }

        ResultSet rs = s.executeQuery();
        JSONObject object;

        while (rs.next()) {
            object = new JSONObject();
            object.put("dist_id", rs.getInt(1));
            object.put("type", rs.getString(2));
            object.put("to_location_id", rs.getInt(3));
            object.put("from_location_id", rs.getInt(4));
            object.put("date_filled", rs.getDate(5));
            object.put("status", rs.getString(6));
            object.put("percent_completed", rs.getFloat(7));
            object.put("date_completed", rs.getDate(8));
            json.put(object);
        }

    } catch (JSONException | SQLException ex) {
        Logger.getLogger(Distributions.class.getName()).log(Level.SEVERE, null, ex);
    }
    return json;
}

From source file:com.alibaba.otter.node.etl.common.db.utils.SqlUtils.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value
 * type./*from w  w  w  .  j ava2  s  . c  o m*/
 * <p>
 * Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>
 * Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * 
 * @param rs is the ResultSet holding the data
 * @param index is the column index
 * @param requiredType the required value type (may be <code>null</code>)
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 */
private static String getResultSetValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value = null;
    boolean wasNullCheck = false;

    // Explicitly extract typed value, as far as possible.
    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = Boolean.valueOf(rs.getBoolean(index));
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = new Byte(rs.getByte(index));
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = new Short(rs.getShort(index));
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = new Long(rs.getLong(index));
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = new Float(rs.getFloat(index));
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = new Double(rs.getDouble(index));
        wasNullCheck = true;
    } else if (java.sql.Time.class.equals(requiredType)) {
        // try {
        // value = rs.getTime(index);
        // } catch (SQLException e) {
        value = rs.getString(index);// ?string0000Time
        // if (value == null && !rs.wasNull()) {
        // value = "00:00:00"; //
        // mysqlzeroDateTimeBehavior=convertToNull0null
        // }
        // }
    } else if (java.sql.Timestamp.class.equals(requiredType) || java.sql.Date.class.equals(requiredType)) {
        // try {
        // value = convertTimestamp(rs.getTimestamp(index));
        // } catch (SQLException e) {
        // ?string0000-00-00 00:00:00Timestamp 
        value = rs.getString(index);
        // if (value == null && !rs.wasNull()) {
        // value = "0000:00:00 00:00:00"; //
        // mysqlzeroDateTimeBehavior=convertToNull0null
        // }
        // }
    } else if (BigDecimal.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (BigInteger.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (Blob.class.equals(requiredType)) {
        value = rs.getBlob(index);
    } else if (Clob.class.equals(requiredType)) {
        value = rs.getClob(index);
    } else if (byte[].class.equals(requiredType)) {
        try {
            byte[] bytes = rs.getBytes(index);
            if (bytes == null) {
                value = null;
            } else {
                value = new String(bytes, "ISO-8859-1");// binaryiso-8859-1
            }
        } catch (UnsupportedEncodingException e) {
            throw new SQLException(e);
        }
    } else {
        // Some unknown type desired -> rely on getObject.
        value = getResultSetValue(rs, index);
    }

    // Perform was-null check if demanded (for results that the
    // JDBC driver returns as primitives).
    if (wasNullCheck && (value != null) && rs.wasNull()) {
        value = null;
    }

    return (value == null) ? null : convertUtilsBean.convert(value);
}

From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value type.
 * <p>Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * @param rs is the ResultSet holding the data
 * @param index is the column index//from   ww w  . j av a  2  s  . c o m
 * @param requiredType the required value type (may be <code>null</code>)
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 */
public static Object getResultSetValue(ResultSet rs, int index, Class requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value = null;
    boolean wasNullCheck = false;

    // Explicitly extract typed value, as far as possible.
    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = Boolean.valueOf(rs.getBoolean(index));
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = Byte.valueOf(rs.getByte(index));
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = Short.valueOf(rs.getShort(index));
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = Integer.valueOf(rs.getInt(index));
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = Long.valueOf(rs.getLong(index));
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = Float.valueOf(rs.getFloat(index));
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = Double.valueOf(rs.getDouble(index));
        wasNullCheck = true;
    } else if (byte[].class.equals(requiredType)) {
        value = rs.getBytes(index);
    } else if (java.sql.Date.class.equals(requiredType)) {
        value = rs.getDate(index);
    } else if (java.sql.Time.class.equals(requiredType)) {
        value = rs.getTime(index);
    } else if (java.sql.Timestamp.class.equals(requiredType) || java.util.Date.class.equals(requiredType)) {
        value = rs.getTimestamp(index);
    } else if (BigDecimal.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (Blob.class.equals(requiredType)) {
        value = rs.getBlob(index);
    } else if (Clob.class.equals(requiredType)) {
        value = rs.getClob(index);
    } else {
        // Some unknown type desired -> rely on getObject.
        value = getResultSetValue(rs, index);
    }

    // Perform was-null check if demanded (for results that the
    // JDBC driver returns as primitives).
    if (wasNullCheck && value != null && rs.wasNull()) {
        value = null;
    }
    return value;
}

From source file:com.mobilewallet.credits.dao.CreditsDAO.java

public List<RechargeHistoryDTO> debitHistory(long userId, int begin, int end) {
    List<RechargeHistoryDTO> list = new ArrayList<RechargeHistoryDTO>();

    Connection connection = null;
    PreparedStatement cstmt = null;
    ResultSet rs = null;
    try {// w  ww.  j  a  v  a  2 s  .  co  m
        connection = dataSource.getConnection();
        cstmt = connection.prepareStatement(debitHistorQuery);
        cstmt.setLong(1, userId);
        cstmt.setInt(2, begin);
        cstmt.setInt(3, end);
        rs = cstmt.executeQuery();
        RechargeHistoryDTO dht = null;
        while (rs.next()) {
            dht = new RechargeHistoryDTO();
            dht.setdTime(rs.getString("d"));
            dht.setAmount(rs.getFloat("wud_amount"));
            dht.setDesc(rs.getString("wud_desc"));
            dht.setCode(rs.getString("wud_code"));
            dht.setDid(rs.getLong("wud_id"));
            dht.setStatus(rs.getString("wud_status"));

            list.add(dht);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (cstmt != null) {
                cstmt.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception ex) {

        }
    }

    return list;
}

From source file:org.carlspring.tools.csv.dao.CSVDao.java

private String getField(ResultSet resultSet, int i, Field field) throws SQLException {
    // Handle primitives
    if (field.getType().equals("int")) {
        return String.valueOf(resultSet.getInt(i));
    } else if (field.getType().equals("long")) {
        return String.valueOf(resultSet.getLong(i));
    } else if (field.getType().equals("float")) {
        return String.valueOf(resultSet.getFloat(i));
    } else if (field.getType().equals("double")) {
        return String.valueOf(resultSet.getDouble(i));
    } else if (field.getType().equals("boolean")) {
        return String.valueOf(resultSet.getBoolean(i));
    }// w  w  w.j a v  a2s .c  o m
    // Handle objects
    else if (field.getType().equals("java.lang.String")) {
        return String.valueOf(resultSet.getString(i));
    } else if (field.getType().equals("java.sql.Date")) {
        return String.valueOf(resultSet.getDate(i));
    } else if (field.getType().equals("java.sql.Timestamp")) {
        return String.valueOf(resultSet.getTimestamp(i));
    } else if (field.getType().equals("java.math.BigDecimal")) {
        return String.valueOf(resultSet.getBigDecimal(i));
    }

    return null;
}