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.springframework.jdbc.support.JdbcUtils.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 a2s.  co m
 * @param requiredType the required value type (may be {@code null})
 * @return the value object (possibly not of the specified required type,
 * with further conversion steps necessary)
 * @throws SQLException if thrown by the JDBC API
 * @see #getResultSetValue(ResultSet, int)
 */
@Nullable
public static Object getResultSetValue(ResultSet rs, int index, @Nullable Class<?> requiredType)
        throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value;

    // Explicitly extract typed value, as far as possible.
    if (String.class == requiredType) {
        return rs.getString(index);
    } else if (boolean.class == requiredType || Boolean.class == requiredType) {
        value = rs.getBoolean(index);
    } else if (byte.class == requiredType || Byte.class == requiredType) {
        value = rs.getByte(index);
    } else if (short.class == requiredType || Short.class == requiredType) {
        value = rs.getShort(index);
    } else if (int.class == requiredType || Integer.class == requiredType) {
        value = rs.getInt(index);
    } else if (long.class == requiredType || Long.class == requiredType) {
        value = rs.getLong(index);
    } else if (float.class == requiredType || Float.class == requiredType) {
        value = rs.getFloat(index);
    } else if (double.class == requiredType || Double.class == requiredType || Number.class == requiredType) {
        value = rs.getDouble(index);
    } else if (BigDecimal.class == requiredType) {
        return rs.getBigDecimal(index);
    } else if (java.sql.Date.class == requiredType) {
        return rs.getDate(index);
    } else if (java.sql.Time.class == requiredType) {
        return rs.getTime(index);
    } else if (java.sql.Timestamp.class == requiredType || java.util.Date.class == requiredType) {
        return rs.getTimestamp(index);
    } else if (byte[].class == requiredType) {
        return rs.getBytes(index);
    } else if (Blob.class == requiredType) {
        return rs.getBlob(index);
    } else if (Clob.class == requiredType) {
        return rs.getClob(index);
    } else if (requiredType.isEnum()) {
        // Enums can either be represented through a String or an enum index value:
        // leave enum type conversion up to the caller (e.g. a ConversionService)
        // but make sure that we return nothing other than a String or an Integer.
        Object obj = rs.getObject(index);
        if (obj instanceof String) {
            return obj;
        } else if (obj instanceof Number) {
            // Defensively convert any Number to an Integer (as needed by our
            // ConversionService's IntegerToEnumConverterFactory) for use as index
            return NumberUtils.convertNumberToTargetClass((Number) obj, Integer.class);
        } else {
            // e.g. on Postgres: getObject returns a PGObject but we need a String
            return rs.getString(index);
        }
    }

    else {
        // Some unknown type desired -> rely on getObject.
        try {
            return rs.getObject(index, requiredType);
        } catch (AbstractMethodError err) {
            logger.debug("JDBC driver does not implement JDBC 4.1 'getObject(int, Class)' method", err);
        } catch (SQLFeatureNotSupportedException ex) {
            logger.debug("JDBC driver does not support JDBC 4.1 'getObject(int, Class)' method", ex);
        } catch (SQLException ex) {
            logger.debug("JDBC driver has limited support for JDBC 4.1 'getObject(int, Class)' method", ex);
        }

        // Corresponding SQL types for JSR-310 / Joda-Time types, left up
        // to the caller to convert them (e.g. through a ConversionService).
        String typeName = requiredType.getSimpleName();
        if ("LocalDate".equals(typeName)) {
            return rs.getDate(index);
        } else if ("LocalTime".equals(typeName)) {
            return rs.getTime(index);
        } else if ("LocalDateTime".equals(typeName)) {
            return rs.getTimestamp(index);
        }

        // Fall back to getObject without type specification, again
        // left up to the caller to convert the value if necessary.
        return getResultSetValue(rs, index);
    }

    // Perform was-null check if necessary (for results that the JDBC driver returns as primitives).
    return (rs.wasNull() ? null : value);
}

From source file:staff.cashier.CashierController.java

@FXML
private void onClickGetPayment(ActionEvent e)
        throws SQLException, IOException, ClassNotFoundException, DocumentException, DecoderException {
    PendingBill currBill = cashierView.getSelectionModel().getSelectedItem();
    System.out.println(currBill.getCusName() + " " + currBill.getOrderID() + " " + currBill.getBill());

    int orderid = currBill.getOrderID();
    int bill_status = 1;
    Statement st = conn.createStatement();
    Statement st1 = conn.createStatement();
    Statement st2 = conn.createStatement();
    // set bill status 1 in order_info table.
    String query = "update order_info set bill_paid='" + bill_status + "' where order_id='"
            + currBill.getOrderID() + "'";
    st.executeUpdate(query);/*from  www.j av a2s.  c o m*/
    // set cus_id=0 in corrosponding table.
    String query1 = "select * from order_info where order_id='" + currBill.getOrderID() + "'";
    ResultSet rs = st1.executeQuery(query1);
    rs.next();
    BigInteger cus_id = new BigInteger(Long.toString(rs.getLong("c_id")));
    BigInteger new_cid = BigInteger.ZERO;
    String query2 = "update table_info set c_id='" + new_cid + "',order_taken=0 where c_id='" + cus_id + "'";
    st2.executeUpdate(query2);

    //deleting the row
    ObservableList<PendingBill> billSelected, allBill;
    allBill = cashierView.getItems();

    allBill.remove((currBill));

    //Inserting into `bill` schema
    int counter = 0;
    //fetching the bill_id of the last order
    query = "select * from bill";
    rs = st.executeQuery(query);
    while (rs.next()) {
        counter = rs.getInt("bill_id");

    }

    counter++;
    String query3 = "insert into bill values(" + counter + "," + currBill.bill + ")";
    st.executeUpdate(query3);
    //Updating the bill_generation schema
    String query4 = "insert into bill_generation values(" + currBill.orderID + ",'" + caid + "'," + counter
            + ")";
    st.executeUpdate(query4);

    //GENERATING THE BILL IN PDF FORM
    String query5 = "select * from order_info where order_id=" + orderid + " ";
    ResultSet rs1 = st.executeQuery(query5);
    rs1.next();
    String itemList = rs1.getString("list");
    int tis = rs1.getInt("table_id");
    float cc = rs1.getFloat("cost");
    //String itemDetails=rs1.getString("item_qty");
    int coupon = rs1.getInt("coupon_id");

    float disc_p = 0;
    //FETCHING THE DISCOUNT PERCENT CORRESPONDING TO THAT COUPON
    if (coupon != 0) {
        Statement st4 = conn.createStatement();
        String q4 = "select discount_percent from coupon where coupon_id=" + coupon;
        ResultSet rs4 = st4.executeQuery(q4);
        rs4.next();
        disc_p = rs4.getFloat("discount_percent");

    }
    //FETCHING CUSTOMER NAME
    String query6 = "select * from customer where c_id=" + cus_id + "";
    ResultSet rs2 = st.executeQuery(query6);
    rs2.next();
    String cusname = rs2.getString("c_name");
    String email = rs2.getString("c_email");

    String itemsInfo = "";
    /*----------------DESERIALIZATION
    ByteArrayInputStream in = new ByteArrayInputStream(Hex.decodeHex(itemList.toCharArray()));
      String[] aa= (String[]) (new ObjectInputStream(in).readObject());
     //System.out.println(Arrays.toString();
      try{
     for (String aa1 : aa) {
     if(aa1!=null){
         int i;
      String tmp="";
     for( i=0;i<(aa1.length()-1);i++)
     {
                 
         tmp+=aa1.charAt(i);
     }
     int qty=Integer.parseInt(""+aa1.charAt(i));
     itemsInfo+="Item name:    "+tmp+"  Qty:"+qty+"\n\n";
             
     }
     }
      }
      catch(Exception ee){}
    -----------------------------------------*/

    //EXTRACTING INFORMATION ABOUT ORDERED ITEMS
    String tmp = "";
    for (int i = 0; i < (itemList.length() - 1); i++) {
        if (itemList.charAt(i + 1) == '-') {
            int qty = Integer.parseInt("" + itemList.charAt(i));
            Statement st3 = conn.createStatement();
            String q3 = "Select price from menu where d_name='" + tmp + "'";
            ResultSet rs3 = st3.executeQuery(q3);
            rs3.next();
            float p = rs3.getFloat("price");
            itemsInfo += "Item name:" + tmp + "  Qty:" + qty + "  Price:+" + p + "    Total:" + (qty * p)
                    + "\n\n";

            tmp = "";
            i++;
        } else
            tmp += itemList.charAt(i);
    }

    itemsInfo += "Total Cost :" + cc + "\n\n";
    if (coupon != 0) {
        float tprice = cc - ((disc_p * cc) / 100);
        itemsInfo += "You have been given a discount of " + disc_p + "%\n\nFinal Cost     :   Rs." + tprice
                + "\n\n";
    }
    System.out.println("Item info:" + itemsInfo);
    //WRITING TO PDF
    Document doc = new Document();

    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("Order" + orderid + ".pdf"));
    doc.open();
    doc.addTitle("CENTRICO RESTAURANT");
    doc.addCreationDate();
    doc.addSubject("BILL");
    //System.out.println(itemDetails);

    doc.add(new Paragraph("                         CENTRICO RESTAURANT\n\nORDER ID     :   " + orderid
            + "\n\nTABLE ID       :   " + tis + "\n\nCUSTOMER NAME     :   " + cusname
            + "\n\nEMAIL ID       :   " + email + "\n\n" + itemsInfo + "\n\n"));

    doc.close();
    writer.close();

    //SENDING THE BILL IN MAIL TO THE CUSTOMER
    GmailQuickstart a = new GmailQuickstart();
    a.setCusemail(email);
    a.setCusmessage("Thankyou so much " + cusname
            + " for coming here.Please visit us again :) \n Please find your bill attached below\n");
    a.setCussubject("Bill for order number " + orderid);
    a.setFileName("Order" + orderid + ".pdf");
    Thread t = new Thread(a);
    t.start();

    //alert
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setTitle("Information dialog");
    alert.setHeaderText(null);
    alert.setContentText(" Payment has Received Successfully");
    alert.showAndWait();
}

From source file:gsi.pushlet.PushletCaronte.java

private JSONArray getCatastrofes(String fecha) {
    JSONArray array = new JSONArray();
    try {//from   www  . j ava 2  s. c o m
        Class.forName(Constantes.DB_DRIVER);
        Connection conexion = DriverManager.getConnection(Constantes.DB_URL, Constantes.DB_USER,
                Constantes.DB_PASS);
        Statement s = conexion.createStatement();
        String query = "SELECT C.ID, CANTIDAD, NOMBRE, C.DESCRIPCION, INFO, LATITUD, "
                + "LONGITUD, DIRECCION, SIZE, TRAFFIC, PLANTA, IDASSIGNED, FECHA, MODIFICADO, "
                + "USUARIO, TIPO_MARCADOR, TIPO_CATASTROFE, TIPO_ESTADO "
                + "FROM CATASTROFES C, TIPOS_MARCADORES M, TIPOS_CATASTROFES T, TIPOS_ESTADOS E "
                + "WHERE MODIFICADO > '" + fecha + "' AND MARCADOR = M.ID AND TIPO = T.ID AND ESTADO = E.ID";
        ResultSet rs = s.executeQuery(query);

        if (rs.next()) {
            JSONObject objeto = new JSONObject();
            objeto.put("id", rs.getInt(1));
            objeto.put("quantity", rs.getInt(2));
            objeto.put("name", rs.getString(3));
            objeto.put("description", rs.getString(4));
            objeto.put("info", rs.getString(5));
            objeto.put("latitud", rs.getFloat(6));
            objeto.put("longitud", rs.getFloat(7));
            objeto.put("address", rs.getString(8));
            objeto.put("size", rs.getString(9));
            objeto.put("traffic", rs.getString(10));
            objeto.put("floor", rs.getInt(11));
            objeto.put("idassigned", rs.getInt(12));
            objeto.put("date", rs.getString(13));
            objeto.put("modified", rs.getString(14));
            objeto.put("user", rs.getInt(15));
            objeto.put("item", rs.getString(16));
            objeto.put("type", rs.getString(17));
            objeto.put("state", rs.getString(18));
            array.put(objeto);
        }

        conexion.close();
    } catch (ClassNotFoundException ex) {
        System.out.println("ClassNotFoundExcepcion: " + ex);
    } catch (SQLException ex) {
        System.out.println("SQLExcepcion: " + ex);
    } catch (JSONException ex) {
        System.out.println("JSONExcepcion: " + ex);
    }

    return array;
}

From source file:net.solarnetwork.node.dao.jdbc.consumption.test.JdbcConsumptionDatumDaoTest.java

@Test
public void storeNew() {
    ConsumptionDatum datum = new ConsumptionDatum(TEST_SOURCE_ID, TEST_AMPS, TEST_VOLTS);
    datum.setCreated(new Date());
    datum.setWattHourReading(TEST_WATT_HOUR_READING);

    dao.storeDatum(datum);//ww  w .j av a2 s . co  m

    jdbcOps.query(SQL_GET_BY_ID,
            new Object[] { new java.sql.Timestamp(datum.getCreated().getTime()), TEST_SOURCE_ID },
            new ResultSetExtractor<Object>() {

                @Override
                public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
                    assertTrue("Must have one result", rs.next());

                    int col = 1;

                    String s = rs.getString(col++);
                    assertFalse(rs.wasNull());
                    assertEquals(TEST_SOURCE_ID, s);

                    rs.getTimestamp(col++);
                    assertFalse(rs.wasNull());

                    Float f = rs.getFloat(col++);
                    assertFalse(rs.wasNull());
                    assertEquals(TEST_VOLTS.doubleValue(), f.doubleValue(), 0.001);

                    f = rs.getFloat(col++);
                    assertFalse(rs.wasNull());
                    assertEquals(TEST_AMPS.doubleValue(), f.doubleValue(), 0.001);

                    Long l = rs.getLong(col++);
                    assertFalse(rs.wasNull());
                    assertEquals(TEST_WATT_HOUR_READING, l);

                    assertFalse("Must not have more than one result", rs.next());
                    return null;
                }

            });
}

From source file:org.apache.hadoop.chukwa.rest.services.SystemMetricsHome.java

private static SystemMetrics createSystemMetrics(ResultSet rs) {
    SystemMetrics obj = null;/*from   w w w.j av  a2s. co m*/
    try {
        obj = new SystemMetrics(rs.getTimestamp("timestamp"), rs.getString("host"),

                rs.getDouble("load_15"), rs.getDouble("load_5"), rs.getDouble("load_1"),
                rs.getDouble("task_total"), rs.getDouble("task_running"), rs.getDouble("task_sleep"),
                rs.getDouble("task_stopped"), rs.getDouble("task_zombie"), rs.getDouble("mem_total"),
                rs.getDouble("mem_buffers"), rs.getDouble("mem_cached"), rs.getDouble("mem_used"),
                rs.getDouble("mem_free"), rs.getDouble("eth0_rxerrs"), rs.getDouble("eth0_rxbyts"),
                rs.getDouble("eth0_rxpcks"), rs.getDouble("eth0_rxdrops"), rs.getDouble("eth0_txerrs"),
                rs.getDouble("eth0_txbyts"), rs.getDouble("eth0_txpcks"), rs.getDouble("eth0_txdrops"),
                rs.getDouble("eth1_rxerrs"), rs.getDouble("eth1_rxbyts"), rs.getDouble("eth1_rxpcks"),
                rs.getDouble("eth1_rxdrops"), rs.getDouble("eth1_txerrs"), rs.getDouble("eth1_txbyts"),
                rs.getDouble("eth1_txpcks"), rs.getDouble("eth1_txdrops"), rs.getDouble("sda_rkbs"),
                rs.getDouble("sda_wkbs"), rs.getDouble("sdb_rkbs"), rs.getDouble("sdb_wkbs"),
                rs.getDouble("sdc_rkbs"), rs.getDouble("sdc_wkbs"), rs.getDouble("sdd_rkbs"),
                rs.getDouble("sdd_wkbs"), rs.getFloat("cpu_idle_pcnt"), rs.getFloat("cpu_nice_pcnt"),
                rs.getFloat("cpu_system_pcnt"), rs.getFloat("cpu_user_pcnt"), rs.getFloat("cpu_hirq_pcnt"),
                rs.getFloat("cpu_sirq_pcnt"), rs.getFloat("iowait_pcnt"), rs.getFloat("mem_buffers_pcnt"),
                rs.getFloat("mem_used_pcnt"), rs.getFloat("eth0_busy_pcnt"), rs.getFloat("eth1_busy_pcnt"),
                rs.getFloat("sda_busy_pcnt"), rs.getFloat("sdb_busy_pcnt"), rs.getFloat("sdc_busy_pcnt"),
                rs.getFloat("sdd_busy_pcnt"), rs.getFloat("swap_used_pcnt"));
    } catch (Exception e) {
    }
    return obj;
}

From source file:org.arkanos.aos.api.data.Goal.java

/**
 * Fetches all goals from a user./*  ww w .  j ava 2s.com*/
 * 
 * @param user_name
 *            defines the user.
 * @return all goals or null, in case there are connection problems.
 */
static public Vector<Goal> getUserGoals(String user_name) {
    try {
        ResultSet rs = Database.query("SELECT * FROM " + Goal.TABLE_NAME + " WHERE " + Goal.FIELD_USER_NAME
                + " = \"" + user_name + "\";");
        Vector<Goal> results = new Vector<Goal>();
        while ((rs != null) && rs.next()) {
            Goal newone = new Goal(rs.getInt(Goal.FIELD_ID), rs.getString(Goal.FIELD_TITLE),
                    rs.getInt(Goal.FIELD_TIME_PLANNED), rs.getString(Goal.FIELD_DESCRIPTION), user_name);
            //TODO: Can this query be optimized?
            ResultSet newrs = Database
                    .query("SELECT AVG(help.progress) AS completion, SUM(help.spent) AS total_time_spent FROM ("
                            + "SELECT IF(SUM((w." + Work.FIELD_RESULT + ")/(t." + Task.FIELD_TARGET + "-t."
                            + Task.FIELD_INITIAL + ")) IS NULL, 0, SUM((w." + Work.FIELD_RESULT + ")/(t."
                            + Task.FIELD_TARGET + "-t." + Task.FIELD_INITIAL + "))) AS progress, " + "SUM("
                            + Work.FIELD_TIME_SPENT + ") AS spent FROM goal g " + "LEFT JOIN " + Task.TABLE_NAME
                            + " t on t." + Task.FIELD_GOAL_ID + " = g." + Goal.FIELD_ID + " " + "LEFT JOIN "
                            + Work.TABLE_NAME + " w ON t." + Task.FIELD_ID + " = w." + Work.FIELD_TASK_ID + " "
                            + "WHERE g." + Goal.FIELD_ID + " = " + newone.getID() + " " + "AND g."
                            + Goal.FIELD_USER_NAME + " = \"" + user_name + "\"" + "GROUP BY t." + Task.FIELD_ID
                            + ",g." + Goal.FIELD_ID + ") help;");
            if ((newrs != null) && newrs.next()) {
                newone.setCompletion(newrs.getFloat("completion"));
                newone.setTotalTimeSpent(newrs.getInt("total_time_spent"));
            }

            results.add(newone);

        }
        return results;
    } catch (SQLException e) {
        Log.error("Goal", "Problems retrieving all goals from a user.");
        e.printStackTrace();
    }
    return null;
}

From source file:org.snaker.engine.access.jdbc.JdbcHelper.java

/**
 * ?ResultSet?index?requiredType?// ww w  .  ja v  a2  s  .c om
 * @param rs
 * @param index
 * @param requiredType
 * @return
 * @throws SQLException
 */
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;

    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = rs.getBoolean(index);
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = rs.getByte(index);
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = rs.getShort(index);
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = rs.getInt(index);
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = rs.getLong(index);
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = rs.getFloat(index);
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = 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 {
        value = getResultSetValue(rs, index);
    }

    if (wasNullCheck && value != null && rs.wasNull()) {
        value = null;
    }
    return value;
}

From source file:org.hyperic.hq.plugin.sybase.SybaseMeasurementPlugin.java

private float getMonitorConfigValue(Connection conn, String configOpt, String prop)
        throws MetricUnreachableException, MetricNotFoundException {
    Statement stmt = null;/*  w  ww  . j  av  a  2  s .co  m*/
    ResultSet rs = null;
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery("sp_monitorconfig '" + configOpt + "'");
        if (rs.next()) {
            return rs.getFloat(prop);
        } else {
            throw new MetricNotFoundException(prop);
        }
    } catch (SQLException e) {
        throw new MetricUnreachableException(e.getMessage(), e);
    } finally {
        DBUtil.closeJDBCObjects(log, null, stmt, rs);
    }
}

From source file:staff.Waiter.MenuController.java

@FXML
private void onClickgetListButton(ActionEvent e) throws SQLException, IOException {
    getMenuButton.setDisable(true);//from   www . j ava  2 s  .  c  om
    String itemInfo = "";
    Statement st = conn.createStatement();
    ObservableList<Menu> totallist = menutable.getItems();
    ObservableList<Menu> orderlist = FXCollections.observableArrayList();
    float tprice = 0;
    int ttime = 0;
    String itemDetails = "";//"ITEM NAME               PRICE       QUANTITY    TOTAL\n\n";
    for (Menu i : totallist) {
        if (Integer.parseInt(i.getMquantity()) > 0) {
            orderlist.add(i);
            System.out.println("Id:" + i.getMid() + " Item : " + i.getMname() + " Price " + i.getMprice()
                    + " Quantity: " + i.getMquantity());
            tprice += (i.getMprice() * Integer.parseInt(i.getMquantity()));

            String query = "select ttime from menu where d_id='" + i.getMid() + "'";
            ResultSet rs = st.executeQuery(query);
            rs.next();
            ttime += (rs.getInt("ttime") * Integer.parseInt(i.getMquantity()));
            System.out.println("Total time:" + ttime);

            //itemDetails+=""+i.getMname()+"               Rs."+i.getMprice()+"           "+i.getMquantity()+"          "+(i.getMprice() * Integer.parseInt(i.getMquantity()))+"\n\n";
            itemDetails += "Item    :" + i.getMname() + "       Price    :" + i.getMprice() + "      Qty    :"
                    + i.getMquantity() + "        Total    :"
                    + (i.getMprice() * Integer.parseInt(i.getMquantity())) + "\n\n";
            s[idx++] = i.getMname() + "" + i.getMquantity();
            itemInfo += i.getMname() + "" + i.getMquantity() + "-";

        }
    }

    itemDetails += "TOTAL COST : " + tprice + "\n\n";

    int couponGiven = 0;
    //Checking the validity of coupon if it exists
    if (!couponTextField.getText().equals("")) {

        int coupon = Integer.parseInt(couponTextField.getText());
        couponGiven = coupon;
        String q = "select * from coupon where coupon_id='" + coupon + "' ";
        ResultSet rs1 = st.executeQuery(q);
        if (rs1.next()) {
            Alert a = new Alert(Alert.AlertType.CONFIRMATION);
            a.setTitle("Confirmation");
            a.setHeaderText(null);
            a.setContentText("Great!!Customer has a valid coupon");
            a.showAndWait();

            float discount = rs1.getFloat("discount_percent");
            tprice -= (tprice * discount) / 100;

            itemDetails += "You have been given a discount of " + discount + "%\n\nFinal Cost     :   Rs."
                    + tprice + "\n\n";
        } else {
            Alert a = new Alert(Alert.AlertType.ERROR);
            a.setTitle("Error");
            a.setHeaderText(null);
            a.setContentText("The coupon is not a valid one!!!!");
            a.showAndWait();
        }

    }

    System.out.println("total price:" + tprice);
    totalPrice.setText("Total bill" + tprice);
    //Making an entry in `order` table
    //serialization
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    new ObjectOutputStream(out).writeObject(s);

    String list = new String(Hex.encodeHex(out.toByteArray()));
    System.out.println("IN BYTE FORM:" + list);

    //for unique order_id
    int counter = 0;
    //fetching the c_id of the last customer
    String query = "select * from order_info";
    ResultSet rs = st.executeQuery(query);
    System.out.println("Counter:" + counter);
    while (rs.next()) {
        counter = rs.getInt("order_id");

    }

    counter++;
    System.out.println("Counter:" + counter);
    String status = "pending";
    //PLACING ORDER
    String q = "insert into order_info (list,table_id,time,status,cost,waiter_id,bill_paid,c_id,coupon_id) values('"
            + itemInfo + "'," + tableId + "," + ttime + ",'" + status + "'," + tprice + ",'" + wid + "',0,"
            + c_id + "," + couponGiven + ")";
    System.out.println("here:" + q);
    st.executeUpdate(q);
    //UPDATING TABLE_INFO
    q = "update table_info set order_taken=1 where t_id=" + tableId + " ";
    st.executeUpdate(q);
    //UPDATING `book_and_order
    q = "insert into book_and_order values(" + tableId + "," + counter + "," + c_id + ")";
    st.executeUpdate(q);
}

From source file:org.waarp.common.database.data.AbstractDbData.java

/**
 * Get one value into DbValue from ResultSet
 * //from  w  w  w. j a  va2  s .  co m
 * @param rs
 * @param value
 * @throws WaarpDatabaseSqlException
 */
static public void getTrueValue(ResultSet rs, DbValue value) throws WaarpDatabaseSqlException {
    try {
        switch (value.type) {
        case Types.VARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.LONGVARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.BIT:
            value.value = rs.getBoolean(value.column);
            break;
        case Types.TINYINT:
            value.value = rs.getByte(value.column);
            break;
        case Types.SMALLINT:
            value.value = rs.getShort(value.column);
            break;
        case Types.INTEGER:
            value.value = rs.getInt(value.column);
            break;
        case Types.BIGINT:
            value.value = rs.getLong(value.column);
            break;
        case Types.REAL:
            value.value = rs.getFloat(value.column);
            break;
        case Types.DOUBLE:
            value.value = rs.getDouble(value.column);
            break;
        case Types.VARBINARY:
            value.value = rs.getBytes(value.column);
            break;
        case Types.DATE:
            value.value = rs.getDate(value.column);
            break;
        case Types.TIMESTAMP:
            value.value = rs.getTimestamp(value.column);
            break;
        case Types.CLOB:
            value.value = rs.getClob(value.column).getCharacterStream();
            break;
        case Types.BLOB:
            value.value = rs.getBlob(value.column).getBinaryStream();
            break;
        default:
            throw new WaarpDatabaseSqlException("Type not supported: " + value.type + " for " + value.column);
        }
    } catch (SQLException e) {
        DbSession.error(e);
        throw new WaarpDatabaseSqlException("Getting values in error: " + value.type + " for " + value.column,
                e);
    }
}