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:com.mobilewallet.common.dao.LoginDAO.java

public User login(String email, String password) {
    User user = null;/*from   w ww.jav a 2  s.c o m*/
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        connection = dataSource.getConnection();
        pstmt = connection.prepareStatement(loginEmailAndPwdQuery);
        pstmt.setString(1, email);
        pstmt.setString(2, password);

        rs = pstmt.executeQuery();

        if (rs.next()) {
            user = new User();
            user.setUserId(rs.getLong("u_id"));
            user.setEmail(rs.getString("u_email"));
            user.setName(rs.getString("u_name"));
            user.setMyRefCode(rs.getString("u_my_ref_code"));
            user.setFriendRefCode(rs.getString("u_friend_ref_code"));
            user.setAmount(rs.getFloat("w_amount"));
            log.info("Amount In DAO : " + rs.getFloat("w_amount"));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception ex) {

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

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

        }
    }
    return user;
}

From source file:br.bookmark.db.util.ResultSetUtils.java

/**
 * Map JDBC objects to Java equivalents.
 * Used by getBean() and getBeans().//from ww w.ja v  a2 s  .  c om
 * <p>
 * Some types not supported.
 * Many not work with all drivers.
 * <p>
 * Makes binary conversions of BIGINT, DATE, DECIMAL, DOUBLE, FLOAT, INTEGER,
 * REAL, SMALLINT, TIME, TIMESTAMP, TINYINT.
 * Makes Sting conversions of CHAR, CLOB, VARCHAR, LONGVARCHAR, BLOB, LONGVARBINARY,
 * VARBINARY.
 * <p>
 * DECIMAL, INTEGER, SMALLINT, TIMESTAMP, CHAR, VARCHAR tested with MySQL and Poolman.
 * Others not guaranteed.
 * @param classeDestino 
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 */
private static void putEntry(Map properties, ResultSetMetaData metaData, ResultSet resultSet, int i,
        Class classeDestino) throws Exception {

    /*
    In a perfect universe, this would be enough
    properties.put(
        metaData.getColumnName(i),
        resultSet.getObject(i));
    But only String, Timestamp, and Integer seem to get through that way.
    */

    String columnName = metaData.getColumnName(i);

    // Testa se  uma FK
    /*Field[] fields = classeDestino.getDeclaredFields();
    for (int j = 0; j < fields.length; j++) {
    if (fields[j].getAnnotation(DBFK.class) != null) {
        properties.put(columnName, resultSet.getString(i));
    }
    }*/
    //System.out.println(i+"-"+metaData.getColumnType(i));
    switch (metaData.getColumnType(i)) {

    // http://java.sun.com/j2se/1.3.0/docs/api/java/sql/Types.html

    case Types.BIGINT:
        properties.put(columnName, new Long(resultSet.getLong(i)));
        break;

    case Types.DATE:
        properties.put(columnName, resultSet.getDate(i));
        break;

    case Types.DECIMAL:
    case Types.DOUBLE:
        properties.put(columnName, new Double(resultSet.getDouble(i)));
        break;

    case Types.FLOAT:
        properties.put(columnName, new Float(resultSet.getFloat(i)));
        break;

    case Types.INTEGER:
        int valor = 0;
        try { // Se o campo esta vazio d erro
            valor = resultSet.getInt(i);
        } catch (SQLException e) {
        }
        properties.put(columnName, new Integer(valor));
        break;

    case Types.REAL:
        properties.put(columnName, new Double(resultSet.getString(i)));
        break;

    case Types.SMALLINT:
        properties.put(columnName, new Short(resultSet.getShort(i)));
        break;

    case Types.TIME:
        properties.put(columnName, resultSet.getTime(i));
        break;

    case Types.TIMESTAMP:
        properties.put(columnName, resultSet.getTimestamp(i));
        break;

    // :FIXME: Throws java.lang.ClassCastException: java.lang.Integer
    // :FIXME: with Poolman and MySQL unless use getString.
    case Types.TINYINT:
        properties.put(columnName, new Byte(resultSet.getString(i)));
        break;

    case Types.CHAR:
    case Types.CLOB:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        // :FIXME: Handle binaries differently?
    case Types.BLOB:
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
        properties.put(columnName, resultSet.getString(i));
        break;

    /*
        :FIXME: Add handlers for
        ARRAY
        BINARY
        BIT
        DISTINCT
        JAVA_OBJECT
        NULL
        NUMERIC
        OTHER
        REF
        STRUCT
    */

    // Otherwise, pass as *String property to be converted
    default:
        properties.put(columnName + "String", resultSet.getString(i));
        break;
    } // end switch

}

From source file:com.linkage.community.schedule.dbutils.CustomScalarHandler.java

/**
 * Returns one <code>ResultSet</code> column as an object via the
 * <code>ResultSet.getObject()</code> method that performs type
 * conversions.//ww w .j a  va  2  s  .  com
 * @param rs <code>ResultSet</code> to process.
 * @return The column or <code>null</code> if there are no rows in
 * the <code>ResultSet</code>.
 *
 * @throws SQLException if a database access error occurs
 * @throws ClassCastException if the class datatype does not match the column type
 *
 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
 */
// We assume that the user has picked the correct type to match the column
// so getObject will return the appropriate type and the cast will succeed.

@SuppressWarnings("unchecked")
//@Override
public T handle(ResultSet rs) throws SQLException {
    Object obj = null;
    if (rs.next()) {
        if (this.columnName == null) {
            obj = rs.getObject(this.columnIndex);
            if (obj instanceof Integer)
                return (T) (obj = rs.getInt(columnIndex));
            else if (obj instanceof Long)
                return (T) (obj = (new Long(rs.getLong(columnIndex)).intValue()));
            else if (obj instanceof Boolean)
                return (T) (obj = rs.getBoolean(columnIndex));
            else if (obj instanceof Double)
                return (T) (obj = rs.getDouble(columnIndex));
            else if (obj instanceof Float)
                return (T) (obj = rs.getFloat(columnIndex));
            else if (obj instanceof Short)
                return (T) (obj = rs.getShort(columnIndex));
            else if (obj instanceof Byte)
                return (T) (obj = rs.getByte(columnIndex));
            else
                return (T) obj;
        } else {
            obj = rs.getObject(this.columnName);
            if (obj instanceof Integer)
                return (T) (obj = rs.getInt(columnName));
            else if (obj instanceof Long)
                return (T) (obj = rs.getLong(columnName));
            else if (obj instanceof Boolean)
                return (T) (obj = rs.getBoolean(columnName));
            else if (obj instanceof Double)
                return (T) (obj = rs.getDouble(columnName));
            else if (obj instanceof Float)
                return (T) (obj = rs.getFloat(columnName));
            else if (obj instanceof Short)
                return (T) (obj = rs.getShort(columnName));
            else if (obj instanceof Byte)
                return (T) (obj = rs.getByte(columnName));
            else
                return (T) obj;
        }
    }
    return null;
}

From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void setColumnValue(final ResultSet rs, final StructAttributeReflect attr,
        final AbstractEntity entity, final AbstractJoinGraph gr, final Stack<KeyValuePair<Class<?>>> path)
        throws Exception {

    KeyValuePair<String> alias = gr.getAliasFor(path, attr.Column, 0);
    String tabprefix = alias.getKey();

    if (EnumPrimitives.isPrimitiveType(attr.Field.getType())) {
        EnumPrimitives prim = EnumPrimitives.type(attr.Field.getType());
        switch (prim) {
        case ECharacter:
            String sv = rs.getString(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), sv.charAt(0));
            }//from w  ww  .  j  av  a  2  s. c  om
            break;
        case EShort:
            short shv = rs.getShort(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), shv);
            }
            break;
        case EInteger:
            int iv = rs.getInt(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), iv);
            }
            break;
        case ELong:
            long lv = rs.getLong(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), lv);
            }
            break;
        case EFloat:
            float fv = rs.getFloat(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), fv);
            }
            break;
        case EDouble:
            double dv = rs.getDouble(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dv);
            }
            break;
        default:
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else if (attr.Convertor != null) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            attr.Convertor.load(entity, attr.Column, value);
        }
    } else if (attr.Field.getType().equals(String.class)) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), value);
        }
    } else if (attr.Field.getType().equals(Date.class)) {
        long value = rs.getLong(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Date dt = new Date(value);
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dt);
        }
    } else if (attr.Field.getType().isEnum()) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Class ecls = attr.Field.getType();
            Object evalue = Enum.valueOf(ecls, value);
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), evalue);
        }
    } else if (attr.Reference != null) {
        Class<?> rt = Class.forName(attr.Reference.Class);
        Object obj = rt.newInstance();
        if (!(obj instanceof AbstractEntity))
            throw new Exception("Unsupported Entity type [" + rt.getCanonicalName() + "]");
        AbstractEntity rentity = (AbstractEntity) obj;
        if (path.size() > 0) {
            path.peek().setKey(attr.Column);
        }

        KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>();
        cls.setValue(rentity.getClass());
        path.push(cls);
        setEntity(rentity, rs, gr, path);
        PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), rentity);
        path.pop();
    }
}

From source file:com.l2jfree.gameserver.datatables.CharTemplateTable.java

private CharTemplateTable() {
    Connection con = null;//from ww w .j  av  a 2 s.  c  o  m

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement("SELECT * FROM class_list, char_templates, lvlupgain"
                + " WHERE class_list.id = char_templates.classId" + " AND class_list.id = lvlupgain.classId"
                + " ORDER BY class_list.id");
        ResultSet rset = statement.executeQuery();

        int size = 0;
        while (rset.next()) {
            StatsSet set = new StatsSet();
            set.set("classId", rset.getInt("id"));
            set.set("className", rset.getString("className"));
            set.set("raceId", rset.getInt("raceId"));
            set.set("baseSTR", rset.getInt("STR"));
            set.set("baseCON", rset.getInt("CON"));
            set.set("baseDEX", rset.getInt("DEX"));
            set.set("baseINT", rset.getInt("_INT"));
            set.set("baseWIT", rset.getInt("WIT"));
            set.set("baseMEN", rset.getInt("MEN"));
            set.set("baseHpMax", rset.getFloat("defaultHpBase"));
            set.set("lvlHpAdd", rset.getFloat("defaultHpAdd"));
            set.set("lvlHpMod", rset.getFloat("defaultHpMod"));
            set.set("baseMpMax", rset.getFloat("defaultMpBase"));
            set.set("baseCpMax", rset.getFloat("defaultCpBase"));
            set.set("lvlCpAdd", rset.getFloat("defaultCpAdd"));
            set.set("lvlCpMod", rset.getFloat("defaultCpMod"));
            set.set("lvlMpAdd", rset.getFloat("defaultMpAdd"));
            set.set("lvlMpMod", rset.getFloat("defaultMpMod"));
            set.set("baseHpReg", 1.5);
            set.set("baseMpReg", 0.9);
            set.set("basePAtk", rset.getInt("p_atk"));
            set.set("basePDef", /*classId.isMage()? 77 : 129*/rset.getInt("p_def"));
            set.set("baseMAtk", rset.getInt("m_atk"));
            set.set("baseMDef", rset.getInt("char_templates.m_def"));
            set.set("classBaseLevel", rset.getInt("class_lvl"));
            set.set("basePAtkSpd", rset.getInt("p_spd"));
            set.set("baseMAtkSpd", /*classId.isMage()? 166 : 333*/rset.getInt("char_templates.m_spd"));
            set.set("baseCritRate", rset.getInt("char_templates.critical") / 10);
            set.set("baseRunSpd", rset.getInt("move_spd") * Config.RATE_RUN_SPEED);
            set.set("baseWalkSpd", 0);
            set.set("baseShldDef", 0);
            set.set("baseShldRate", 0);
            set.set("baseAtkRange", 40);

            /* Not a single point
            set.set("spawnX", rset.getInt("x"));
            set.set("spawnY", rset.getInt("y"));
            set.set("spawnZ", rset.getInt("z"));
            */

            L2PlayerTemplate ct;

            set.set("collision_radius", rset.getDouble("m_col_r"));
            set.set("collision_height", rset.getDouble("m_col_h"));
            // Add-on for females
            set.set("fcollision_radius", rset.getDouble("f_col_r"));
            set.set("fcollision_height", rset.getDouble("f_col_h"));
            ct = new L2PlayerTemplate(set);

            _templates[ct.getClassId().getId()] = ct;
            size++;
        }

        rset.close();
        statement.close();

        _log.info("CharTemplateTable: Loaded " + size + " Character Templates.");
    } catch (SQLException e) {
        _log.fatal("Failed loading char templates", e);
    }

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con
                .prepareStatement("SELECT classId, itemId, amount, equipped FROM char_creation_items");
        ResultSet rset = statement.executeQuery();

        int classId, itemId, amount;
        boolean equipped;
        while (rset.next()) {
            classId = rset.getInt("classId");
            itemId = rset.getInt("itemId");
            amount = rset.getInt("amount");
            equipped = rset.getString("equipped").equals("true");

            if (ItemTable.getInstance().getTemplate(itemId) != null) {
                if (classId == -1) {
                    for (L2PlayerTemplate pct : _templates) {
                        if (pct == null)
                            continue;

                        pct.addItem(itemId, amount, equipped);
                    }
                } else {
                    L2PlayerTemplate pct = _templates[classId];
                    if (pct != null) {
                        pct.addItem(itemId, amount, equipped);
                    } else {
                        _log.warn("char_creation_items: Entry for undefined class, classId: " + classId);
                    }
                }
            } else {
                _log.warn("char_creation_items: No data for itemId: " + itemId + " defined for classId "
                        + classId);
            }
        }
        rset.close();
        statement.close();
    } catch (SQLException e) {
        _log.fatal("Failed loading char creation items.", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:staff.cashier.CashierController.java

@FXML
private void onClickPendingBill(ActionEvent e) {
    ObservableList<PendingBill> list = FXCollections.observableArrayList();
    try {//from ww w  .  j a v a  2  s  .co  m
        Statement st = conn.createStatement();
        int billstatus = 0;
        String status = "finished";

        String query = "select * from order_info where bill_paid=" + billstatus + " and status='" + status
                + "'";
        ResultSet rs = st.executeQuery(query);
        // int f=0;
        while (rs.next()) {
            // f++;
            System.out.println("in cashierCntroller");
            BigInteger id = new BigInteger(Long.toString(rs.getLong("c_id")));
            System.out.println("cid:" + id);
            Statement st1 = conn.createStatement();
            String query1 = "select * from customer where c_id=" + id + "";
            ResultSet rs1 = st1.executeQuery(query1);
            rs1.next();
            System.out.println("Name:" + rs1.getString("c_name"));
            PendingBill a = new PendingBill(rs.getInt("order_id"), rs1.getString("c_name"),
                    rs.getFloat("cost"));
            list.add(a);
        }

        // if(f!=0)
        cashierView.getItems().addAll(list);

    } catch (SQLException ex) {
        Logger.getLogger(CurrentOrderController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.georepublic.db.utils.ResultSetConverter.java

public static StringBuffer convertCsv(ResultSet rs) throws SQLException {

    String column_name = new String();
    StringBuffer retval = new StringBuffer();
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();

    for (int h = 1; h < numColumns + 1; h++) {
        column_name = rsmd.getColumnName(h);

        if (h > 1) {
            retval.append(",");
        }/*from  ww  w .  j a  v  a 2  s .com*/

        retval.append(column_name);
    }
    retval.append("\n");

    while (rs.next()) {

        for (int i = 1; i < numColumns + 1; i++) {
            column_name = rsmd.getColumnName(i);

            if (StringUtils.equals(column_name, "the_geom")) {
                continue;
            }
            if (StringUtils.equals(column_name, "geojson")) {
                continue;
            }
            if (i > 1) {
                retval.append(",");
            }

            if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                retval.append(rs.getArray(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                retval.append(rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                retval.append(rs.getBlob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                retval.append(rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                retval.append(rs.getFloat(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                retval.append(rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                retval.append(rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                retval.append(rs.getDate(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                retval.append(rs.getTimestamp(column_name));
            } else {
                retval.append(rs.getObject(column_name));
            }

        }
        retval.append("\n");
    }

    return retval;
}

From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object getColumnValue(final ResultSet rs, final StructAttributeReflect attr,
        final AbstractEntity entity, final AbstractJoinGraph gr, final Stack<KeyValuePair<Class<?>>> path)
        throws Exception {

    Object value = null;/*  w  w  w  .  j  a va2 s.  c  o m*/

    KeyValuePair<String> alias = gr.getAliasFor(path, attr.Column, 0);
    String tabprefix = alias.getKey();

    if (EnumPrimitives.isPrimitiveType(attr.Field.getType())) {
        EnumPrimitives prim = EnumPrimitives.type(attr.Field.getType());
        switch (prim) {
        case ECharacter:
            String sv = rs.getString(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), sv.charAt(0));
            }
            break;
        case EShort:
            short shv = rs.getShort(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), shv);
            }
            break;
        case EInteger:
            int iv = rs.getInt(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), iv);
            }
            break;
        case ELong:
            long lv = rs.getLong(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), lv);
            }
            break;
        case EFloat:
            float fv = rs.getFloat(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), fv);
            }
            break;
        case EDouble:
            double dv = rs.getDouble(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dv);
            }
            break;
        default:
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else if (attr.Convertor != null) {
        // TODO : Not supported at this time.
        value = rs.getString(tabprefix + "." + attr.Column);

    } else if (attr.Field.getType().equals(String.class)) {
        value = rs.getString(tabprefix + "." + attr.Column);
        if (rs.wasNull()) {
            value = null;
        }
    } else if (attr.Field.getType().equals(Date.class)) {
        long lvalue = rs.getLong(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Date dt = new Date(lvalue);
            value = dt;
        }
    } else if (attr.Field.getType().isEnum()) {
        String svalue = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Class ecls = attr.Field.getType();
            value = Enum.valueOf(ecls, svalue);
        }
    } else if (attr.Reference != null) {
        Class<?> rt = Class.forName(attr.Reference.Class);
        Object obj = rt.newInstance();
        if (!(obj instanceof AbstractEntity))
            throw new Exception("Unsupported Entity type [" + rt.getCanonicalName() + "]");
        AbstractEntity rentity = (AbstractEntity) obj;
        if (path.size() > 0) {
            path.peek().setKey(attr.Column);
        }

        KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>();
        cls.setValue(rentity.getClass());
        path.push(cls);
        setEntity(rentity, rs, gr, path);
        value = rentity;
        path.pop();
    }
    return value;
}

From source file:com.oracle.tutorial.jdbc.CoffeesTable.java

public void modifyPricesByPercentage(String coffeeName, float priceModifier, float maximumPrice)
        throws SQLException {
    con.setAutoCommit(false);//from ww  w .  j a  va2 s  . c  om

    Statement getPrice = null;
    Statement updatePrice = null;
    ResultSet rs = null;
    String query = "SELECT COF_NAME, PRICE FROM COFFEES " + "WHERE COF_NAME = '" + coffeeName + "'";

    try {
        Savepoint save1 = con.setSavepoint();
        getPrice = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        updatePrice = con.createStatement();

        if (!getPrice.execute(query)) {
            System.out.println("Could not find entry for coffee named " + coffeeName);
        } else {
            rs = getPrice.getResultSet();
            rs.first();
            float oldPrice = rs.getFloat("PRICE");
            float newPrice = oldPrice + (oldPrice * priceModifier);
            System.out.println("Old price of " + coffeeName + " is " + oldPrice);
            System.out.println("New price of " + coffeeName + " is " + newPrice);
            System.out.println("Performing update...");
            updatePrice.executeUpdate(
                    "UPDATE COFFEES SET PRICE = " + newPrice + " WHERE COF_NAME = '" + coffeeName + "'");
            System.out.println("\nCOFFEES table after update:");
            CoffeesTable.viewTable(con);
            if (newPrice > maximumPrice) {
                System.out.println("\nThe new price, " + newPrice + ", is greater than the maximum " + "price, "
                        + maximumPrice + ". Rolling back the transaction...");
                con.rollback(save1);
                System.out.println("\nCOFFEES table after rollback:");
                CoffeesTable.viewTable(con);
            }
            con.commit();
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (getPrice != null) {
            getPrice.close();
        }
        if (updatePrice != null) {
            updatePrice.close();
        }
        con.setAutoCommit(true);
    }
}

From source file:uk.ac.ebi.orchem.search.SimilaritySearch.java

/**
 * Similarity score calculation between one database compound and a user's query compound.
 * @param userQuery  query structure in SMILES or MOL
 * @param queryType  MOL or SMILES/*from www  .  j  a  va  2  s.  c  o  m*/
 * @param compoundId ID of database compound to calculate similarity with
 * @return tanimoto similarity score
 * @throws Exception
 */
public static float singleCompoundSimilarity(Clob userQuery, String queryType, String compoundId)
        throws Exception {

    OracleConnection conn = null;
    PreparedStatement pstmtFp = null;
    ResultSet resFp = null;
    float tanimotoCoeff = 0;

    try {
        //User query
        int clobLen = new Long(userQuery.length()).intValue();
        String query = (userQuery.getSubString(1, clobLen));
        IAtomContainer molecule = null;
        if (queryType.equals(Utils.QUERY_TYPE_MOL)) {
            molecule = MoleculeCreator.getMoleculeFromMolfile(query);
        } else if (queryType.equals(Utils.QUERY_TYPE_SMILES)) {
            SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance());
            molecule = sp.parseSmiles(query);
        } else
            throw new RuntimeException("Query type not recognized");
        BitSet queryFp = FingerPrinterAgent.FP.getExtendedFingerPrinter().getFingerprint(molecule);
        float queryBitCount = queryFp.cardinality();
        byte[] queryBytes = Utils.toByteArray(queryFp, extFpSize);

        //Database comound
        conn = (OracleConnection) new OracleDriver().defaultConnection();
        String compoundQuery = "select bit_count, fp from orchem_fingprint_simsearch s where id=?";
        pstmtFp = conn.prepareStatement(compoundQuery);
        pstmtFp.setFetchSize(1);
        pstmtFp.setString(1, compoundId);
        resFp = pstmtFp.executeQuery();

        if (resFp.next()) {
            byte[] dbByteArray = resFp.getBytes("fp");
            float compoundBitCount = resFp.getFloat("bit_count");
            tanimotoCoeff = calcTanimoto(queryBytes, queryBytes.length, dbByteArray, queryBitCount,
                    compoundBitCount);
        } else
            throw new RuntimeException("Compound " + compoundId + " not found in similarity table");

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (resFp != null)
            resFp.close();
        if (pstmtFp != null)
            pstmtFp.close();
        if (conn != null)
            conn.close();
    }
    return tanimotoCoeff;
}