List of usage examples for java.sql ResultSet getDouble
double getDouble(String columnLabel) throws SQLException;
ResultSet
object as a double
in the Java programming language. 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 w ww .j a va 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.sfs.whichdoctor.dao.ExpenseClaimDAOImpl.java
/** * Load expense claim./*from w ww. ja v a2s. c om*/ * * @param rs the rs * @return the expense claim bean * @throws SQLException the sQL exception */ private ExpenseClaimBean loadExpenseClaim(final ResultSet rs) throws SQLException { ExpenseClaimBean expenseClaim = new ExpenseClaimBean(); expenseClaim.setId(rs.getInt("ExpenseClaimId")); expenseClaim.setGUID(rs.getInt("GUID")); expenseClaim.setReferenceGUID(rs.getInt("ReferenceGUID")); expenseClaim.setExpenseClass(rs.getString("ExpenseClass")); expenseClaim.setExpenseType(rs.getString("ExpenseType")); expenseClaim.setCurrencyAbbreviation(rs.getString("CurrencyAbbreviation")); try { expenseClaim.setExpenseDate(rs.getDate("ExpenseDate")); } catch (SQLException sqe) { dataLogger.debug("Error loading ExpenseDate: " + sqe.getMessage()); } expenseClaim.setExchangeRate(rs.getDouble("ExchangeRate")); expenseClaim.setDescription(rs.getString("Description")); expenseClaim.setRate(rs.getDouble("Rate")); expenseClaim.setQuantity(rs.getInt("Quantity")); expenseClaim.setGSTRate(rs.getDouble("GSTRate")); expenseClaim.setValue(rs.getDouble("Value")); expenseClaim.setNetValue(rs.getDouble("NetValue")); expenseClaim.setActive(rs.getBoolean("Active")); try { expenseClaim.setCreatedDate(rs.getTimestamp("CreatedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage()); } expenseClaim.setCreatedBy(rs.getString("CreatedBy")); try { expenseClaim.setModifiedDate(rs.getTimestamp("ModifiedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage()); } expenseClaim.setModifiedBy(rs.getString("ModifiedBy")); return expenseClaim; }
From source file:com.sfs.whichdoctor.analysis.AgedDebtorsAnalysisDAOImpl.java
/** * Load receipt map, where integer = guid of person/organisation. * * @param analysis the analysis/*from w w w. ja va 2 s . c o m*/ * @return the hash map of receipts */ @SuppressWarnings("unchecked") private HashMap<Integer, ReceiptBean> loadLastReceipts(final AgedDebtorsAnalysisBean analysis) { HashMap<Integer, ReceiptBean> lastReceipts = new HashMap<Integer, ReceiptBean>(); StringBuffer sql = new StringBuffer(); sql.append(this.getSQL().getValue("agedDebtors/lastReceipts")); sql.append(" WHERE "); sql.append(buildSqlWhere(analysis, "fs1.PersonId", "fs1.OrganisationId", false)); sql.append(" GROUP BY fs1.PersonId"); if (dataLogger.isDebugEnabled()) { dataLogger.debug("SQL: " + sql.toString()); } Collection<ReceiptBean> receipts = new ArrayList<ReceiptBean>(); try { receipts = this.getJdbcTemplateReader().query(sql.toString(), new Object[] {}, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { ReceiptBean receipt = new ReceiptBean(); receipt.setGUID(rs.getInt("Id")); receipt.setAbbreviation(rs.getString("Abbreviation")); receipt.setNumber(rs.getString("Number")); receipt.setPersonId(rs.getInt("PersonId")); receipt.setOrganisationId(rs.getInt("OrganisationId")); receipt.setNetValue(rs.getDouble("NetValue")); try { receipt.setIssued(rs.getDate("Issued")); } catch (SQLException sqe) { dataLogger.error("Error loading issued date: " + sqe.getMessage()); } return receipt; } }); } catch (IncorrectResultSizeDataAccessException ie) { // No results found for this search dataLogger.debug("No results found for this search: " + ie.getMessage()); } for (ReceiptBean receipt : receipts) { if (receipt.getPersonId() > 0) { lastReceipts.put(receipt.getPersonId(), receipt); } if (receipt.getOrganisationId() > 0) { lastReceipts.put(receipt.getOrganisationId(), receipt); } } return lastReceipts; }
From source file:ui.Analyze.java
private void genaratePermintaan(LocalDate awal, LocalDate akhir) throws SQLException { org.jfree.data.general.DefaultPieDataset data = new org.jfree.data.general.DefaultPieDataset(); javax.swing.table.DefaultTableModel m = new javax.swing.table.DefaultTableModel( new String[] { "Nama Barang", "Jumlah" }, 0) { @Override//w w w . j a v a 2s. c o m public boolean isCellEditable(int row, int column) { return false; } }; tblMinta.setModel(m); java.sql.PreparedStatement p = d.getPS( "select detjual.brg,sum(detjual.jum)as qty from jual left join detjual on jual.nota=detjual.nota " + "where jual.tgl>=? and " + "jual.tgl<=? group by detjual.brg"); p.setDate(1, Date.valueOf(awal)); p.setDate(2, Date.valueOf(akhir)); java.sql.ResultSet r = p.executeQuery(); while (r.next()) { String brg = r.getString("brg"); double qty = r.getDouble("qty"); data.setValue(brg, qty); m.addRow(new String[] { brg, "" + qty }); } r.close(); p.close(); org.jfree.chart.ChartPanel cp = new org.jfree.chart.ChartPanel( ChartFactory.createPieChart("Permintaan", data, true, true, false)); cp.setSize(pnlMinta.getSize()); if (0 < pnlMinta.getComponentCount()) pnlMinta.removeAll(); pnlMinta.add(cp); }
From source file:com.sfs.whichdoctor.analysis.RevenueAnalysisDAOImpl.java
/** * Load batch revenue./*from w w w . j av a 2 s . c o m*/ * * @param rs the rs * @return the revenue bean * @throws SQLException the sQL exception */ private RevenueBean loadBatchRevenue(final ResultSet rs) throws SQLException { final RevenueBean revenue = new RevenueBean(); revenue.setBatchReference(rs.getInt("BatchReference")); revenue.setBatchNo(rs.getString("BatchNo")); if (revenue.getBatchNo() == null) { revenue.setBatchNo(rs.getString("BatchReference")); } if (revenue.getBatchNo().compareTo("") == 0) { revenue.setBatchNo(rs.getString("BatchReference")); } revenue.setValue(rs.getDouble("RevenueValue")); revenue.setNetValue(rs.getDouble("RevenueNetValue")); final double gstRate = rs.getDouble("InvoiceGSTRate"); revenue.setGSTValue(gstRate, revenue.getGSTValue()); /** Temporary placeholder for Receipt details */ ReceiptBean receipt = loadReceipt(rs); PaymentBean payment = new PaymentBean(); payment.setIncomeStream(rs.getString("RevenueType")); payment.setValue(rs.getDouble("RevenueValue")); payment.setNetValue(rs.getDouble("RevenueNetValue")); /* Load invoice details */ if (rs.getInt("InvoiceGUID") > 0) { payment.setDebit(loadDebit(rs)); } Collection<PaymentBean> payments = new ArrayList<PaymentBean>(); payments.add(payment); receipt.setPayments(payments); TreeMap<Integer, ReceiptBean> receipts = new TreeMap<Integer, ReceiptBean>(); receipts.put(new Integer(receipt.getId()), receipt); revenue.setReceipts(receipts); return revenue; }
From source file:lineage2.loginserver.accounts.Account.java
/** * Method restore.// w ww.j av a 2 s. com */ public void restore() { Connection con = null; PreparedStatement statement = null; ResultSet rset = null; try { con = L2DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement( "SELECT password, access_level, ban_expire, allow_ip, bonus, bonus_expire, last_server, last_ip, last_access FROM accounts WHERE login = ?"); statement.setString(1, login); rset = statement.executeQuery(); if (rset.next()) { setPasswordHash(rset.getString("password")); setAccessLevel(rset.getInt("access_level")); setBanExpire(rset.getInt("ban_expire")); setAllowedIP(rset.getString("allow_ip")); setBonus(rset.getDouble("bonus")); setBonusExpire(rset.getInt("bonus_expire")); setLastServer(rset.getInt("last_server")); setLastIP(rset.getString("last_ip")); setLastAccess(rset.getInt("last_access")); } } catch (Exception e) { _log.error("", e); } finally { DbUtils.closeQuietly(con, statement, rset); } }
From source file:com.imagelake.android.purchasemanagement.Servlet_purchaseVisePackages.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); try {//from w w w . j a v a2s .co m String type = request.getParameter("type"); String sql = "SELECT SQL_CALC_FOUND_ROWS user_has_packages.purchase_date,user_has_packages.expire_date,user_has_packages.user_id,user_has_packages.state,admin_package_income.total" + " FROM user_has_packages,admin_package_income WHERE user_has_packages.uhp_id=admin_package_income.uhp_id "; if (type != null && !type.equals("")) { if (type.equals("all")) { sql += "ORDER BY user_has_packages.purchase_date DESC "; ja = new JSONArray(); System.out.println("sql=" + sql); PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) { rs.close(); rs = ps.executeQuery(); while (rs.next()) { JSONObject jo = new JSONObject(); DecimalFormat df = new DecimalFormat(); jo.put("pur_date", rs.getString(1)); jo.put("exp_date", rs.getString(2)); jo.put("un", udi.getUn(rs.getInt(3))); if (rs.getInt(4) == 1) { jo.put("state", 1); } else if (rs.getInt(4) == 2) { jo.put("state", 2); } jo.put("income", df.format(rs.getDouble(5))); ja.add(jo); } System.out.println(ja.toJSONString()); out.write("json=" + ja.toJSONString()); } else { out.write("msg=No item found."); } } else if (type.equals("sort")) { ja = new JSONArray(); String from = request.getParameter("date"); String to = request.getParameter("date2"); String cat = request.getParameter("cat"); String buy = request.getParameter("buy"); System.out.println("date_pur:" + from); System.out.println("date_exp:" + to); System.out.println("cat:" + cat); System.out.println("buy:" + buy); if (cat.equals("0")) { cat = ""; } if (from != null && !from.trim().equals("") && to != null && !to.trim().equals("")) { String[] dt = from.split("-"); String[] dt2 = to.split("-"); String orDate = dt[2] + "-" + dt[1] + "-" + dt[0]; String orDate2 = dt2[2] + "-" + dt2[1] + "-" + dt2[0]; System.out.println("date=" + orDate); sql += " AND user_has_packages.purchase_date BETWEEN '" + orDate + "' AND '" + orDate2 + "' "; } if (cat != null && !cat.trim().equals("")) { sql += " AND user_has_packages.package_type='" + cat + "' "; } if (buy != null && !buy.trim().equals("")) { sql += " AND user_has_packages.user_id='" + buy + "' "; } sql += "ORDER BY user_has_packages.purchase_date DESC "; System.out.println("sql: " + sql); PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql); ResultSet rs = ps.executeQuery(); DecimalFormat df = new DecimalFormat(); if (rs.next()) { rs.close(); rs = ps.executeQuery(); while (rs.next()) { JSONObject jo = new JSONObject(); jo.put("pur_date", rs.getString(1)); jo.put("exp_date", rs.getString(2)); jo.put("un", udi.getUn(rs.getInt(3))); if (rs.getInt(4) == 1) { jo.put("state", 1); } else if (rs.getInt(4) == 2) { jo.put("state", 2); } jo.put("income", df.format(rs.getDouble(5))); ja.add(jo); } System.out.println(ja.toJSONString()); out.write("json=" + ja.toJSONString()); } else { out.write("msg=No item found."); } } } else { out.write("msg=Internal server error,Please try again later."); } } catch (Exception e) { e.printStackTrace(); out.write("msg=Internal server error,Please try again later."); } }
From source file:com.sfs.dao.FinancialTypeDAOImpl.java
/** * Load details./*w w w. ja v a 2s . c om*/ * * @param rs the rs * * @return the financial type bean * * @throws SQLException the SQL exception */ private FinancialTypeBean loadDetails(final ResultSet rs) throws SQLException { FinancialTypeBean financialType = new FinancialTypeBean(); financialType.setFinancialTypeId(rs.getInt("FinancialTypeId")); financialType.setObject(rs.getString("Object")); financialType.setName(rs.getString("Name")); financialType.setClassName(rs.getString("Class")); financialType.setAbbreviation(rs.getString("Abbreviation")); financialType.setSecurity(rs.getString("Security")); financialType.setLdapMapping(1, rs.getString("LdapMapping")); financialType.setLdapMapping(2, rs.getString("SecondLdapMapping")); financialType.setLdapMapping(3, rs.getString("ThirdLdapMapping")); financialType.setValue(rs.getDouble("Value")); financialType.setDescription(rs.getString("Description")); financialType.setCreated(rs.getTimestamp("Created")); financialType.setCreatedBy(rs.getString("CreatedBy")); financialType.setModified(rs.getTimestamp("Modified")); financialType.setModifiedBy(rs.getString("ModifiedBy")); if (financialType.getCreatedBy() != null && this.userDAO != null) { try { financialType.setCreatedByUser(this.userDAO.loadCached(financialType.getCreatedBy())); } catch (Exception e) { dataLogger.info("Could not load CreatedBy UserBean for FinancialTypeId = " + financialType.getFinancialTypeId()); } } if (financialType.getModifiedBy() != null && this.userDAO != null) { try { financialType.setModifiedByUser(this.userDAO.loadCached(financialType.getModifiedBy())); } catch (Exception e) { dataLogger.info("Could not load ModifiedBy UserBean for FinancialTypeId = " + financialType.getFinancialTypeId()); } } return financialType; }
From source file:com.sfs.whichdoctor.analysis.FinancialSummaryAnalysisDAOImpl.java
/** * Gets the running total./*from w ww . ja v a 2s .c o m*/ * * @param sqlWHERE the sql where * @param parameters the parameters * @param date the date * @param summaryId the summary id * * @return the running total */ @SuppressWarnings("unchecked") private double getRunningTotal(final String sqlWHERE, final Collection<Object> parameters, final Date date, final int summaryId) { double runningTotal = 0; runningTotal = getBalance(sqlWHERE, parameters, date, true); // Get a list of all the transactions on the // current day in order to find balance StringBuffer findBalanceSql = new StringBuffer(); findBalanceSql.append(this.getSQL().getValue("financialSummary/find")); findBalanceSql.append(sqlWHERE); findBalanceSql.append(" AND financial_summary.Issued = ?"); findBalanceSql.append(this.sqlORDER); String field = df.format(date); parameters.add(field); dataLogger.info("SQL Query: " + findBalanceSql.toString()); Collection<TransactionSummaryBean> transactions = new ArrayList<TransactionSummaryBean>(); try { transactions = this.getJdbcTemplateReader().query(findBalanceSql.toString(), parameters.toArray(), new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { TransactionSummaryBean transaction = new TransactionSummaryBean(); transaction.setSummaryId(rs.getInt("SummaryId")); transaction.setFinancialType(rs.getString("Class")); transaction.setCategory(rs.getString("Object")); transaction.setValue(rs.getDouble("Value")); transaction.setNetValue(rs.getDouble("NetValue")); transaction.setCancelled(rs.getBoolean("Cancelled")); return transaction; } }); } catch (IncorrectResultSizeDataAccessException ie) { // No results found for this search dataLogger.debug("No results found for search: " + ie.getMessage()); } for (TransactionSummaryBean transaction : transactions) { if (transaction.getSummaryId() != summaryId) { if (!transaction.getCancelled()) { if (StringUtils.equalsIgnoreCase(transaction.getCategory(), "Debit")) { runningTotal += transaction.getNetValue(); } if (StringUtils.equalsIgnoreCase(transaction.getCategory(), "Receipt")) { runningTotal -= transaction.getNetValue(); } if (StringUtils.equalsIgnoreCase(transaction.getCategory(), "Credit")) { if (StringUtils.equalsIgnoreCase(transaction.getFinancialType(), "Refund")) { runningTotal += transaction.getNetValue(); } else { runningTotal -= transaction.getNetValue(); } } } } else { return runningTotal; } } return runningTotal; }
From source file:com.act.lcms.db.model.MS1ScanForWellAndMassCharge.java
@Override protected List<MS1ScanForWellAndMassCharge> fromResultSet(ResultSet resultSet) throws SQLException, IOException, ClassNotFoundException { List<MS1ScanForWellAndMassCharge> results = new ArrayList<>(); while (resultSet.next()) { Integer id = resultSet.getInt(DB_FIELD.ID.getOffset()); Integer plateId = resultSet.getInt(DB_FIELD.PLATE_ID.getOffset()); Integer plateRow = resultSet.getInt(DB_FIELD.PLATE_ROW.getOffset()); Integer plateColumn = resultSet.getInt(DB_FIELD.PLATE_COLUMN.getOffset()); Double maxYAxis = resultSet.getDouble(DB_FIELD.MAX_Y_AXIS.getOffset()); Boolean useSNR = resultSet.getBoolean(DB_FIELD.USE_SNR.getOffset()); String lcmsScanFilePath = resultSet.getString(DB_FIELD.SCAN_FILE.getOffset()); String chemicalName = resultSet.getString(DB_FIELD.CHEMICAL_NAME.getOffset()); List<String> metlinIons = MS1ScanForWellAndMassCharge .deserializeMetlinIons(resultSet.getString(DB_FIELD.METLIN_IONS.getOffset())); Map<String, List<XZ>> ionsToSpectra = MS1ScanForWellAndMassCharge .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_SPECTRA.getOffset())); Map<String, Double> ionsToIntegral = MS1ScanForWellAndMassCharge .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_INTEGRAL.getOffset())); Map<String, Double> ionsToMax = MS1ScanForWellAndMassCharge .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_MAX.getOffset())); Map<String, Double> ionsToLogSNR = MS1ScanForWellAndMassCharge .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_LOG_SNR.getOffset())); Map<String, Double> ionsToAvgSignal = MS1ScanForWellAndMassCharge .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_AVG_SIGNAL.getOffset())); Map<String, Double> ionsToAvgAmbient = MS1ScanForWellAndMassCharge .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_AVG_AMBIENT.getOffset())); Map<String, Double> individualMaxIntensities = MS1ScanForWellAndMassCharge .deserialize(resultSet.getBytes(DB_FIELD.INDIVIDUAL_MAX_INTENSITIES.getOffset())); results.add(new MS1ScanForWellAndMassCharge(id, plateId, plateColumn, plateRow, useSNR, lcmsScanFilePath, chemicalName, metlinIons, ionsToSpectra, ionsToIntegral, ionsToMax, ionsToLogSNR, ionsToAvgSignal, ionsToAvgAmbient, individualMaxIntensities, maxYAxis)); }/*w ww. java2 s.co m*/ return results; }