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:ece356.UserDBAO.java
public static ArrayList<DoctorData> queryDoctor(HashMap<String, String> doctorParam, String user) throws ClassNotFoundException, SQLException { Connection con = null;//from w w w . java 2 s . c o m PreparedStatement pstmt = null; ArrayList<DoctorData> ret; try { con = getConnection(); String query; boolean reviewByFriends = false; if (doctorParam.containsKey("reviewByFriends")) { if (doctorParam.get("reviewByFriends").equals("yes")) { query = "select * from doctorSearchView where username in (select username from doctorSearchView left join review on doctorSearchView.doc_spec_username = review.doc_username where doctorSearchView.patient_username in " + "(select friend.sent_username as friend " + "from friend where friend.isAccepted = 1 AND friend.recieved_username like '%" + user + "%'" + "union " + "select friend.recieved_username as friend " + "from friend where friend.isAccepted = 1 AND friend.sent_username like '%" + user + "%'))"; reviewByFriends = true; } else { query = "SELECT * FROM doctorSearchView "; } doctorParam.remove("reviewByFriends"); } else { query = "SELECT * FROM doctorSearchView "; //pstmt = con.prepareStatement(query); } // Query for general doctor information ArrayList<String> keys = new ArrayList<String>(doctorParam.keySet()); ArrayList<String> values = new ArrayList<String>(doctorParam.values()); HashMap<Integer, Integer> h1 = new HashMap<>(); int counter = 0; if (!keys.isEmpty()) { counter++; if (!reviewByFriends) query = query + " where"; else query = query + " AND"; for (String key : keys) { if (key.equals("averageRating") || key.equals("yearsLicensed")) { query = query + " " + key + " >= ?"; query += " AND"; h1.put(counter, counter); } else if (key.equals("gender")) { query = query + " " + key + " = ?"; query += " AND"; h1.put(counter, counter); } else if (keys.equals("reviewByFriends")) { } else { query = query + " " + key + " LIKE ?"; query += " AND"; } counter++; } query = query.substring(0, query.length() - 4); System.out.println(query); } query += " group by first_name, last_name, gender, averageRating, numberOfReviews"; pstmt = con.prepareStatement(query); if (!values.isEmpty()) { counter = 1; for (String value : values) { if (h1.containsKey(counter)) { pstmt.setString(counter, value); } else { pstmt.setString(counter, "%" + value + "%"); } counter++; } } System.out.println(pstmt); ResultSet resultSet; resultSet = pstmt.executeQuery(); ret = new ArrayList(); while (resultSet.next()) { DoctorData doctor = new DoctorData(); doctor.userName = resultSet.getString("username"); doctor.firstName = resultSet.getString("first_name"); doctor.middleInitial = resultSet.getString("middle_initial"); doctor.lastName = resultSet.getString("last_name"); doctor.gender = resultSet.getString("gender"); doctor.averageRating = resultSet.getDouble("averageRating"); doctor.numberOfReviews = resultSet.getInt("numberOfReviews"); ret.add(doctor); } return ret; } catch (Exception e) { System.out.println("EXCEPTION:%% " + e); } finally { if (pstmt != null) { pstmt.close(); } if (con != null) { con.close(); } } return null; }
From source file:nl.tudelft.stocktrader.derby.DerbyMarketSummaryDAO.java
public Quote getQuote(String symbol) throws DAOException { if (logger.isDebugEnabled()) { logger.debug("MarketSummaryDAO.getQouteForUpdate(String)\nSymbol :" + symbol); }//from www . j a v a 2 s . co m PreparedStatement selectQuote = null; try { selectQuote = sqlConnection.prepareStatement(SQL_SELECT_QUOTE_NOLOCK); selectQuote.setString(1, symbol); ResultSet rs = selectQuote.executeQuery(); try { Quote quote = null; if (rs.next()) { quote = new Quote(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getBigDecimal(4), rs.getBigDecimal(5), rs.getBigDecimal(6), rs.getBigDecimal(7), rs.getDouble(8)); } return quote; } finally { try { rs.close(); } catch (SQLException e) { logger.debug("", e); } } } catch (SQLException e) { throw new DAOException("", e); } finally { try { if (selectQuote != null) { selectQuote.close(); } } catch (SQLException e) { logger.debug("", e); } } }
From source file:fll.web.playoff.Playoff.java
/** * Get the performance score for the given team, tournament and run number * /* w w w . j a va 2 s .c o m*/ * @throws SQLException on a database error * @throws IllegalArgumentException if no score exists */ public static double getPerformanceScore(final Connection connection, final int tournament, final Team team, final int runNumber) throws SQLException, IllegalArgumentException { if (null == team) { throw new IllegalArgumentException("Cannot get score for null team"); } else { PreparedStatement stmt = null; ResultSet rs = null; try { stmt = connection.prepareStatement("SELECT ComputedTotal FROM Performance WHERE TeamNumber = ?" + " AND Tournament = ?" + " AND RunNumber = ?"); stmt.setInt(1, team.getTeamNumber()); stmt.setInt(2, tournament); stmt.setInt(3, runNumber); rs = stmt.executeQuery(); if (rs.next()) { return rs.getDouble(1); } else { throw new IllegalArgumentException("No score exists for tournament: " + tournament + " teamNumber: " + team.getTeamNumber() + " runNumber: " + runNumber); } } finally { SQLFunctions.close(rs); SQLFunctions.close(stmt); } } }
From source file:nl.tudelft.stocktrader.mysql.MySQLMarketSummaryDAO.java
public MarketSummary getCustomMarketSummary() throws DAOException { BigDecimal tSIA = (BigDecimal) StockTraderSQLUtil.executeScalarNoParm(SQL_SELECT_MARKETSUMMARY_TSIA, sqlConnection);/*w ww. j a v a 2s. c om*/ BigDecimal openTSIA = (BigDecimal) StockTraderSQLUtil.executeScalarNoParm(SQL_SELECT_MARKETSUMMARY_OPENTSIA, sqlConnection); double totalVolume = ((Double) StockTraderSQLUtil.executeScalarNoParm(SQL_SELECT_MARKETSUMMARY_VOLUME, sqlConnection)).doubleValue(); List<Quote> topGainers = new ArrayList<Quote>(); PreparedStatement gainers = null; try { gainers = sqlConnection.prepareStatement(SQL_SELECT_MARKETSUMMARY_GAINERS); ResultSet rs = gainers.executeQuery(); try { for (int i = 0; rs.next() && i < 5; i++) { Quote quote = new Quote(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getBigDecimal(4), rs.getBigDecimal(5), rs.getBigDecimal(6), rs.getBigDecimal(7), rs.getDouble(8)); topGainers.add(quote); } } finally { try { rs.close(); } catch (SQLException e) { logger.debug("", e); } } } catch (SQLException e) { throw new DAOException("", e); } finally { if (gainers != null) { try { gainers.close(); } catch (SQLException e) { logger.debug("", e); } } } List<Quote> topLosers = new ArrayList<Quote>(); PreparedStatement losers = null; try { losers = sqlConnection.prepareStatement(SQL_SELECT_MARKETSUMMARY_LOSERS); ResultSet rs = losers.executeQuery(); try { for (int i = 0; rs.next() && i < 5; i++) { Quote quote = new Quote(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getBigDecimal(4), rs.getBigDecimal(5), rs.getBigDecimal(6), rs.getBigDecimal(7), rs.getDouble(8)); topLosers.add(quote); } } finally { try { rs.close(); } catch (SQLException e) { logger.debug("", e); } } } catch (SQLException e) { throw new DAOException("", e); } finally { if (losers != null) { try { losers.close(); } catch (SQLException e) { logger.debug("", e); } } } MarketSummary marketSummary = new MarketSummary(tSIA, openTSIA, totalVolume, topGainers, topLosers); return marketSummary; }
From source file:com.grayfox.server.dao.jdbc.RecommendationJdbcDao.java
@Override public List<Recommendation> findNearestWithHighRating(Location location, Integer radius, Locale locale) { List<Recommendation> recommendations = getJdbcTemplate().query(getQuery("Poi.findNearestWithHighRating"), (ResultSet rs, int i) -> { Recommendation recommendation = new Recommendation(); Poi poi = new Poi(); int columnIndex = 1; poi.setId(rs.getLong(columnIndex++)); poi.setName(rs.getString(columnIndex++)); poi.setLocation(new Location()); poi.getLocation().setLatitude(rs.getDouble(columnIndex++)); poi.getLocation().setLongitude(rs.getDouble(columnIndex++)); poi.setFoursquareId(rs.getString(columnIndex++)); poi.setFoursquareRating(rs.getDouble(columnIndex++)); recommendation.setType(Recommendation.Type.GLOBAL); recommendation.setReason(Messages.get("recommendation.global.reason", locale)); recommendation.setPoi(poi); return recommendation; }, location.getLatitude(), location.getLongitude(), radius); recommendations.forEach(recommendation -> recommendation.getPoi().setCategories(new HashSet<>( categoryDao.findByPoiFoursquareId(recommendation.getPoi().getFoursquareId(), locale)))); return recommendations; }
From source file:nl.tudelft.stocktrader.derby.DerbyMarketSummaryDAO.java
public void updateStockPriceVolume(double quantity, RemoteQuoteData quote) throws DAOException { // BigDecimal priceChangeFactor = StockTraderUtility.getRandomPriceChangeFactor(quote.getPrice()); // BigDecimal newPrice = quote.getPrice().multiply(priceChangeFactor); ////from w w w .j av a 2 s . co m // if (newPrice.compareTo(quote.getLow()) == -1) { // quote.setLow(newPrice); // } // if (newPrice.compareTo(quote.getHigh()) == 1) { // quote.setHigh(newPrice); // } PreparedStatement previousValues = null; PreparedStatement updateStockPriceVolumeStat = null; try { previousValues = sqlConnection.prepareStatement(SQL_SELECT_QUOTE); previousValues.setString(1, quote.getTicker()); ResultSet rs = previousValues.executeQuery(); if (!rs.next()) { throw new DAOException("Could not find quote " + quote.getTicker()); } double low = rs.getDouble("low"); double high = rs.getDouble("high"); if (low > quote.getValue()) { low = quote.getValue(); } if (high < quote.getValue()) { high = quote.getValue(); } BigDecimal value = new BigDecimal(quote.getValue()).setScale(4, RoundingMode.HALF_UP); updateStockPriceVolumeStat = sqlConnection.prepareStatement(SQL_UPDATE_STOCKPRICEVOLUME); updateStockPriceVolumeStat.setBigDecimal(1, value); updateStockPriceVolumeStat.setBigDecimal(2, new BigDecimal(low).setScale(4, RoundingMode.HALF_UP)); updateStockPriceVolumeStat.setBigDecimal(3, new BigDecimal(high).setScale(4, RoundingMode.HALF_UP)); updateStockPriceVolumeStat.setBigDecimal(4, value); updateStockPriceVolumeStat.setFloat(5, (float) quantity); updateStockPriceVolumeStat.setString(6, quote.getTicker()); updateStockPriceVolumeStat.executeUpdate(); } catch (SQLException e) { throw new DAOException("", e); } finally { try { if (updateStockPriceVolumeStat != null) { updateStockPriceVolumeStat.close(); } } catch (SQLException e) { logger.debug("", e); } } }
From source file:com.imagelake.android.account.Servlet_Account.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); try {//from w ww. j a va 2 s. c o m String uid = request.getParameter("uid"); if (uid != null) { User u = udi.getUser(Integer.parseInt(uid)); if (u != null) { if (u.getState() == 1) { JSONObject jo = new JSONObject();//create a JSONObject if (u.getUser_type() != 2 && u.getUser_type() != 3) { double income = 0.0; DecimalFormat df = new DecimalFormat("#.00"); try { String sql = "SELECT SUM(total) FROM admin_package_income"; PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { income = rs.getDouble(1); jo.put("income", df.format(income)); } rs.close(); } catch (Exception e) { e.printStackTrace(); } int usersCount = udi.allUsersCount(); jo.put("users", usersCount); int imagesCount = new ImagesDAOImp().getImagesCount(); jo.put("imgcount", imagesCount); } else { UserHasPackage uss = uhpdi.getUserActivePackage(u.getUser_id(), 1); //check user package------------------------------------------- if (uss != null) { System.out.println(uss.getExpire_date()); System.out.println(date); System.out.println("is expierd:" + uss.getExpire_date().compareTo(date)); if (uss.getExpire_date().compareTo(date) <= 0) { boolean okk = new UserHasPackageDAOImp().updateState(uss.getUhp_id()); } else { if (!uss.getLast_date().equals(date)) { if (uss.getPackage_type() == 1) { //FreeTrial f=new FreeTrialDAOImp().getAFreeTrail(uss.getPackage_type()); UserHasPackage uhpp = new UserHasPackage(); uhpp.setDownload_count(uss.getOrg_downloads()); uhpp.setCredit_count(uss.getCredit_count()); uhpp.setLast_date(date); uhpp.setUhp_id(uss.getUhp_id()); System.gc(); boolean kk = new UserHasPackageDAOImp().updatePackage(uhpp); System.out .println("UPDATE PACKAGE | PACKAGE TYPE IS 1 7 DAY FREE TRIAL"); } else if (uss.getPackage_type() == 2) { //FreeTrial f=new FreeTrialDAOImp().getAFreeTrail(uss.getPackage_type()); Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, uss.getDuration()); UserHasPackage uhpp = new UserHasPackage(); System.out.println( "*******************" + uss.getExpire_date().compareTo(date)); if (uss.getExpire_date().compareTo(date) < 0) { uhpp.setDownload_count(uss.getDownload_count()); uhpp.setCredit_count(uss.getCredit_count()); uhpp.setExpire_date(sdf.format(c.getTime())); uhpp.setLast_date(date); uhpp.setUhp_id(uss.getUhp_id()); System.gc(); boolean kk = new UserHasPackageDAOImp().updateExpireDate(uhpp); System.out.println( "UPDATE EXPIRE DATE | PACKAGE TYPE IS 2 MONTH FREE TRIAL"); } else { uhpp.setDownload_count(uss.getDownload_count()); uhpp.setCredit_count(uss.getCredit_count()); uhpp.setExpire_date(sdf.format(c.getTime())); uhpp.setLast_date(date); uhpp.setUhp_id(uss.getUhp_id()); System.gc(); boolean kk = new UserHasPackageDAOImp().updatePackage(uhpp); System.out.println( "UPDATE JUST LAST DATE | PACKAGE TYPE IS 2 MONTH FREE TRIAL"); } } else if (uss.getPackage_type() == 3) { SubscriptionPackage sp = new SubscriptionPackageDAOImp() .getSubscription(uss.getPackage_id()); if (sp.getSubscription_type_id() != 2) { //DownloadCount dc=new DownloadCountDAOImp().getCount(sp.getCount_id()); UserHasPackage uhpp = new UserHasPackage(); uhpp.setDownload_count(uss.getOrg_downloads()); uhpp.setCredit_count(uss.getCredit_count()); uhpp.setLast_date(date); uhpp.setUhp_id(uss.getUhp_id()); System.gc(); boolean kk = new UserHasPackageDAOImp().updatePackage(uhpp); System.out.println( "UPDATE PACKAGE | PACKAGE TYPE IS 3 SUBSCRIPTION PACKAGE"); } } } } } // UserHasPackage up = uhpdi.getUserPackage(u.getUser_id(), 1, 3); if (up == null) { jo.put("subscription", "Image Subscription"); jo.put("ps1", "You have no active image subscriptions"); jo.put("issNull", "yes"); } else { SubscriptionPackage sp = spdi.getSubscription(up.getPackage_id()); String type = spdi.getSubscriptionType(sp.getSubscription_type_id()); String title = uhpdi.getPackageType(up.getPackage_type()); DownloadCount dc = dcdi.getCount(sp.getCount_id()); int dowPerDay = dc.getCount(); jo.put("subscription", "" + dowPerDay + " images " + type + " " + title + " for " + sp.getDuration() + " Month"); jo.put("ps1", "Purchase Date : " + up.getPurchase_date()); jo.put("ps2", "Expire Date : " + up.getExpire_date()); jo.put("ps3", "you have left " + up.getDownload_count() + " downloads for today"); jo.put("issNull", "no"); } UserHasPackage p = uhpdi.getUserPackage(u.getUser_id(), 1, 4); if (p == null) { jo.put("credits", "Image Credit Packs"); jo.put("pc1", "You have no active credit packs"); jo.put("iscNull", "yes"); // jo.put("pckType","2"); } else { SubscriptionPackage sp = spdi.getSubscription(p.getPackage_id()); String title = uhpdi.getPackageType(p.getPackage_type()); jo.put("credits", p.getCredit_count() + " " + title + " Package"); jo.put("pc1", "Purchase Date : " + p.getPurchase_date()); jo.put("pc2", "Expire Date : " + p.getExpire_date()); jo.put("pc3", "you have left " + p.getCredit_count() + " credits for today"); jo.put("iscNull", "no"); // jo.put("pckType","2"); } } out.write("json=" + jo.toJSONString()); System.out.println("json" + jo.toJSONString()); } else { out.write("msg=Blocked by the admin"); } } else { out.write("msg=Internal server error,Please try again later."); } } else { out.write("msg=Internal server error,Please try again later."); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.jd.survey.dao.survey.QuestionStatisticDAOImp.java
/** * Returns descriptive statistics for numeric question' answers (minimum, maximum, average, standard deviation) * @param question/*from w w w.j a v a2 s.c o m*/ * @return */ private List<QuestionStatistic> getDescriptiveStatistics(Question question, final Long totalRecordCount) { Long surveyDefinitionId = question.getPage().getSurveyDefinition().getId(); Short pageOrder = question.getPage().getOrder(); Short questionOrder = question.getOrder(); final String columnName = "p" + pageOrder + "q" + questionOrder; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("select MIN(d." + columnName + ") as min ,MAX(d." + columnName + ") as max ,AVG(d." + columnName + ") as avg ,STDDEV_SAMP(d." + columnName + ") as std "); stringBuilder.append(" from survey_data_" + surveyDefinitionId + " d inner join survey s on (s.id=d.survey_id and s.status='S')"); String selectSQLStatement = stringBuilder.toString(); List<QuestionStatistic> questionStatistics = this.jdbcTemplate.query(selectSQLStatement, new RowMapper<QuestionStatistic>() { public QuestionStatistic mapRow(ResultSet rs, int rowNum) throws SQLException { QuestionStatistic questionStatistic = new QuestionStatistic(); questionStatistic.setMin(rs.getDouble("min")); questionStatistic.setMax(rs.getDouble("max")); questionStatistic.setAverage(rs.getDouble("avg")); questionStatistic.setSampleStandardDeviation(rs.getDouble("std")); questionStatistic.setTotalCount(totalRecordCount); return questionStatistic; } }); return questionStatistics; }
From source file:nl.tudelft.stocktrader.derby.DerbyMarketSummaryDAO.java
public MarketSummary getCustomMarketSummary() throws DAOException { BigDecimal tSIA = (BigDecimal) StockTraderSQLUtil.executeScalarNoParm(SQL_SELECT_MARKETSUMMARY_TSIA, sqlConnection);/* w w w .ja v a 2 s . c o m*/ BigDecimal openTSIA = (BigDecimal) StockTraderSQLUtil.executeScalarNoParm(SQL_SELECT_MARKETSUMMARY_OPENTSIA, sqlConnection); double totalVolume = ((Float) StockTraderSQLUtil.executeScalarNoParm(SQL_SELECT_MARKETSUMMARY_VOLUME, sqlConnection)).doubleValue(); List<Quote> topGainers = new ArrayList<Quote>(); PreparedStatement gainers = null; try { gainers = sqlConnection.prepareStatement(SQL_SELECT_MARKETSUMMARY_GAINERS); ResultSet rs = gainers.executeQuery(); try { for (int i = 0; rs.next() && i < 5; i++) { Quote quote = new Quote(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getBigDecimal(4), rs.getBigDecimal(5), rs.getBigDecimal(6), rs.getBigDecimal(7), rs.getDouble(8)); topGainers.add(quote); } } finally { try { rs.close(); } catch (SQLException e) { logger.debug("", e); } } } catch (SQLException e) { throw new DAOException("", e); } finally { if (gainers != null) { try { gainers.close(); } catch (SQLException e) { logger.debug("", e); } } } List<Quote> topLosers = new ArrayList<Quote>(); PreparedStatement losers = null; try { losers = sqlConnection.prepareStatement(SQL_SELECT_MARKETSUMMARY_LOSERS); ResultSet rs = losers.executeQuery(); try { for (int i = 0; rs.next() && i < 5; i++) { Quote quote = new Quote(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getBigDecimal(4), rs.getBigDecimal(5), rs.getBigDecimal(6), rs.getBigDecimal(7), rs.getDouble(8)); topLosers.add(quote); } } finally { try { rs.close(); } catch (SQLException e) { logger.debug("", e); } } } catch (SQLException e) { throw new DAOException("", e); } finally { if (losers != null) { try { losers.close(); } catch (SQLException e) { logger.debug("", e); } } } MarketSummary marketSummary = new MarketSummary(tSIA, openTSIA, totalVolume, topGainers, topLosers); return marketSummary; }
From source file:br.com.great.dao.IrLocaisDAO.java
/** * Metodo responsavel por retornar todos os dados de uma entidade irlocias * @param mecanica_id id da mecanica/*from w w w. j a va 2 s .c o m*/ * @return JSONObjet objeto com todos os dados da entidade irlocais */ public IrLocal getMecIrLocais(int mecanica_id) { PreparedStatement pstmt = null; ResultSet rs = null; Connection conexao = criarConexao(); IrLocal irLocais = null; try { String sql = "SELECT * FROM `irlocais` WHERE `irlocais`.`mecanica_id` = " + mecanica_id; pstmt = conexao.prepareStatement(sql); rs = pstmt.executeQuery(); if (rs.next()) { irLocais = new IrLocal(); irLocais.setIrlocal_id(rs.getInt("id")); irLocais.setPosicao(new Posicao(rs.getDouble("latitude"), rs.getDouble("longitude"))); irLocais.setMecsimples_id(rs.getInt("mecanica_id")); } } catch (SQLException e) { System.out.println("Erro ao listar todos os clientes: " + e.getMessage()); } finally { fecharConexao(conexao, pstmt, rs); } return irLocais; }