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:org.dcm4chee.dashboard.ui.report.display.DisplayReportDiagramPanel.java
@Override public void onBeforeRender() { super.onBeforeRender(); Connection jdbcConnection = null; try {/* ww w .j av a2 s .c o m*/ if (report == null) throw new Exception("No report given to render diagram"); jdbcConnection = DatabaseUtils.getDatabaseConnection(report.getDataSource()); ResultSet resultSet = DatabaseUtils.getResultSet(jdbcConnection, report.getStatement(), parameters); ResultSetMetaData metaData = resultSet.getMetaData(); JFreeChart chart = null; resultSet.beforeFirst(); // Line chart - 1 numeric value if (report.getDiagram() == 0) { if (metaData.getColumnCount() != 1) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.1numvalues") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.addValue(resultSet.getDouble(1), metaData.getColumnName(1), String.valueOf(resultSet.getRow())); chart = ChartFactory.createLineChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), new ResourceModel("dashboard.report.reportdiagram.image.row-label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true); // XY Series chart - 2 numeric values } else if (report.getDiagram() == 1) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2numvalues") .wrapOnAssignment(this).getObject()); XYSeries series = new XYSeries(metaData.getColumnName(1) + " / " + metaData.getColumnName(2)); while (resultSet.next()) series.add(resultSet.getDouble(1), resultSet.getDouble(2)); chart = ChartFactory.createXYLineChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(1), metaData.getColumnName(2), new XYSeriesCollection(series), PlotOrientation.VERTICAL, true, true, true); // Category chart - 1 numeric value, 1 comparable value } else if (report.getDiagram() == 2) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.setValue(resultSet.getDouble(1), metaData.getColumnName(1) + " / " + metaData.getColumnName(2), resultSet.getString(2)); chart = new JFreeChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), new CategoryPlot(dataset, new LabelAdaptingCategoryAxis(14, metaData.getColumnName(2)), new NumberAxis(metaData.getColumnName(1)), new CategoryStepRenderer(true))); // Pie chart - 1 numeric value, 1 comparable value (used as category) } else if ((report.getDiagram() == 3) || (report.getDiagram() == 4)) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values") .wrapOnAssignment(this).getObject()); DefaultPieDataset dataset = new DefaultPieDataset(); while (resultSet.next()) dataset.setValue(resultSet.getString(2), resultSet.getDouble(1)); if (report.getDiagram() == 3) // Pie chart 2D chart = ChartFactory .createPieChart(new ResourceModel("dashboard.report.reportdiagram.image.label") .wrapOnAssignment(this).getObject(), dataset, true, true, true); else if (report.getDiagram() == 4) { // Pie chart 3D chart = ChartFactory .createPieChart3D(new ResourceModel("dashboard.report.reportdiagram.image.label") .wrapOnAssignment(this).getObject(), dataset, true, true, true); ((PiePlot3D) chart.getPlot()).setForegroundAlpha( Float.valueOf(new ResourceModel("dashboard.report.reportdiagram.image.alpha") .wrapOnAssignment(this).getObject())); } // Bar chart - 1 numeric value, 2 comparable values (used as category, series) } else if (report.getDiagram() == 5) { if ((metaData.getColumnCount() != 2) && (metaData.getColumnCount() != 3)) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.3values") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.setValue(resultSet.getDouble(1), resultSet.getString(2), resultSet.getString(metaData.getColumnCount())); chart = ChartFactory.createBarChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(2), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true); } int[] winSize = DashboardCfgDelegate.getInstance().getWindowSize("reportDiagramImage"); addOrReplace(new JFreeChartImage("diagram", chart, winSize[0], winSize[1])); final JFreeChart downloadableChart = chart; addOrReplace(new Link<Object>("diagram-download") { private static final long serialVersionUID = 1L; @Override public void onClick() { RequestCycle.get().setRequestTarget(new IRequestTarget() { public void respond(RequestCycle requestCycle) { WebResponse wr = (WebResponse) requestCycle.getResponse(); wr.setContentType("image/png"); wr.setHeader("content-disposition", "attachment;filename=diagram.png"); OutputStream os = wr.getOutputStream(); try { ImageIO.write(downloadableChart.createBufferedImage(800, 600), "png", os); os.close(); } catch (IOException e) { log.error(this.getClass().toString() + ": " + "respond: " + e.getMessage()); log.debug("Exception: ", e); } wr.close(); } @Override public void detach(RequestCycle arg0) { } }); } }.add(new Image("diagram-download-image", ImageManager.IMAGE_DASHBOARD_REPORT_DOWNLOAD) .add(new ImageSizeBehaviour()) .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.downloadlink")))); addOrReplace(new Image("diagram-print-image", ImageManager.IMAGE_DASHBOARD_REPORT_PRINT) .add(new ImageSizeBehaviour()) .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.printbutton"))); addOrReplace(new Label("error-message", "").setVisible(false)); addOrReplace(new Label("error-reason", "").setVisible(false)); } catch (Exception e) { log.error("Exception: " + e.getMessage()); addOrReplace(((DynamicDisplayPage) this.getPage()).new PlaceholderLink("diagram-download") .setVisible(false)); addOrReplace(new Image("diagram-print-image").setVisible(false)); addOrReplace(new Image("diagram").setVisible(false)); addOrReplace(new Label("error-message", new ResourceModel("dashboard.report.reportdiagram.statement.error").wrapOnAssignment(this) .getObject()) .add(new AttributeModifier("class", true, new Model<String>("message-error")))); addOrReplace(new Label("error-reason", e.getMessage()) .add(new AttributeModifier("class", true, new Model<String>("message-error")))); log.debug(getClass() + ": ", e); } finally { try { jdbcConnection.close(); } catch (Exception ignore) { } } }
From source file:com.imagelake.control.UserDAOImp.java
@Override public String getUserRate() { StringBuffer sb = null;// ww w. ja v a 2 s .com sb = new StringBuffer("{'userreg':{"); sb.append("'name':'User Rate',"); sb.append("'rate':["); try { String sql = "select count(user_id),DATE(date) from user group by DATE(date)"; PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql); ResultSet rs = ps.executeQuery(); int max = 0; while (rs.next()) { max++; System.out.println("U1: " + rs.getDouble(1)); System.out.println("U2: " + rs.getString(2)); if (rs.isLast()) { sb.append("{'date':'" + rs.getString(2) + "','value':'" + rs.getDouble(1) + "'}"); } else { sb.append("{'date':'" + rs.getString(2) + "','value':'" + rs.getDouble(1) + "'},"); } } sb.append("],"); if (max % 2 == 0) { sb.append("'max':'" + max + "'"); } else { sb.append("'max':'" + max++ + "'"); } sb.append("}"); sb.append("}"); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }
From source file:com.l2jfree.gameserver.instancemanager.hellbound.HellboundManager.java
private void loadWarpgates() { Connection con = null;/*www. j a v a 2 s . c o m*/ try { con = L2DatabaseFactory.getInstance().getConnection(); PreparedStatement statement = con.prepareStatement("SELECT * FROM hellbounds WHERE variable=?"); statement.setString(1, "warpgates_energy"); ResultSet rset = statement.executeQuery(); if (rset.next()) _warpgateEnergy = rset.getInt("value"); else _warpgateEnergy = 0; rset.close(); statement.setString(1, "warpgatesLastcheck"); rset = statement.executeQuery(); if (rset.next()) { double lastCheck = rset.getDouble("value"); if (System.currentTimeMillis() >= lastCheck + (24 * 60 * 60 * 1000)) { subWarpgateEnergy(10000); try { statement = con.prepareStatement("REPLACE INTO hellbounds VALUES (?,?)"); statement.setString(1, "warpgatesLastcheck"); statement.setDouble(2, System.currentTimeMillis()); statement.execute(); statement.close(); } catch (Exception e) { _log.error("Could not update last warpgates check.", e); return; } } } else _warpgateEnergy = 0; rset.close(); } catch (Exception e) { _log.error("Cannot get warpgates last check.", e); } finally { L2DatabaseFactory.close(con); } }
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;//from w w w . j av a2 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.icsshs.datatransfer.database.impl.QueryBeanProcessor.java
/** * Convert a <code>ResultSet</code> column into an object. Simple * implementations could just call <code>rs.getObject(index)</code> while * more complex implementations could perform type manipulation to match * the column's type to the bean property type. * * <p>/*from ww w.ja va 2 s . c om*/ * This implementation calls the appropriate <code>ResultSet</code> getter * method for the given property type to perform the type conversion. If * the property type doesn't match one of the supported * <code>ResultSet</code> types, <code>getObject</code> is called. * </p> * * @param rs The <code>ResultSet</code> currently being processed. It is * positioned on a valid row before being passed into this method. * * @param index The current column index being processed. * * @param propType The bean property type that this column needs to be * converted into. * * @throws SQLException if a database access error occurs * * @return The object from the <code>ResultSet</code> at the given column * index after optional type processing or <code>null</code> if the column * value was SQL NULL. */ protected Object processColumn(ResultSet rs, int index, Class<?> propType) throws SQLException { if (!propType.isPrimitive() && rs.getObject(index) == null) { return null; } if (propType.equals(String.class)) { return rs.getString(index); } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) { return Integer.valueOf(rs.getInt(index)); } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) { return Boolean.valueOf(rs.getBoolean(index)); } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) { return Long.valueOf(rs.getLong(index)); } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) { return Double.valueOf(rs.getDouble(index)); } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) { return Float.valueOf(rs.getFloat(index)); } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) { return Short.valueOf(rs.getShort(index)); } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) { return Byte.valueOf(rs.getByte(index)); } else if (propType.equals(Timestamp.class)) { return rs.getTimestamp(index); } else if (propType.equals(byte[].class)) { return rs.getBytes(index); } else { return rs.getObject(index); } }
From source file:com.itemanalysis.jmetrik.graph.nicc.NonparametricCurveAnalysis.java
public void evaluateAll() throws SQLException { categoryRegression = new TreeMap<VariableAttributes, KernelRegressionCategories>(); for (VariableAttributes v : variables) { KernelRegressionCategories kCat = new KernelRegressionCategories(v, kernelFunction, bandwidth, uniformDistributionApproximation); categoryRegression.put(v, kCat); }//from w w w .j ava2s . c o m //connect to db Table sqlTable = new Table(tableName.getNameForDatabase()); SelectQuery select = new SelectQuery(); for (VariableAttributes v : variables) { select.addColumn(sqlTable, v.getName().nameForDatabase()); } select.addColumn(sqlTable, regressorVariable.getName().nameForDatabase()); if (hasGroupVariable) select.addColumn(sqlTable, groupByVariable.getName().nameForDatabase()); ResultSet rs = null; Statement stmt = null; try { stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(select.toString()); KernelRegressionCategories kernelRegressionCategories; Object itemResponse; Double score; Object tempGroup; String group; while (rs.next()) { //increment kernel regression objects //omit examinees with missing data score = rs.getDouble(regressorVariable.getName().nameForDatabase()); if (!rs.wasNull()) { for (VariableAttributes v : categoryRegression.keySet()) { kernelRegressionCategories = categoryRegression.get(v); itemResponse = rs.getObject(v.getName().nameForDatabase()); if (itemResponse != null) kernelRegressionCategories.increment(score, itemResponse); } } updateProgress(); } } catch (SQLException ex) { throw ex; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } this.firePropertyChange("progress-ind-on", null, null); }
From source file:com.opensymphony.module.propertyset.database.JDBCPropertySet.java
protected Object get(int type, String key) throws PropertyException { String sql = "SELECT " + colItemType + ", " + colString + ", " + colDate + ", " + colData + ", " + colFloat + ", " + colNumber + " FROM " + tableName + " WHERE " + colItemKey + " = ? AND " + colGlobalKey + " = ?"; Object o = null;/* w w w. j a va2 s. c om*/ Connection conn = null; try { conn = ds.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, key); ps.setString(2, globalKey); int propertyType; ResultSet rs = ps.executeQuery(); if (rs.next()) { propertyType = rs.getInt(colItemType); if (propertyType != type) { throw new InvalidPropertyTypeException(); } switch (type) { case PropertySet.BOOLEAN: int boolVal = rs.getInt(colNumber); o = new Boolean(boolVal == 1); break; case PropertySet.DATA: o = rs.getBytes(colData); break; case PropertySet.DATE: o = rs.getTimestamp(colDate); break; case PropertySet.DOUBLE: o = new Double(rs.getDouble(colFloat)); break; case PropertySet.INT: o = new Integer(rs.getInt(colNumber)); break; case PropertySet.LONG: o = new Long(rs.getLong(colNumber)); break; case PropertySet.STRING: o = rs.getString(colString); break; default: throw new InvalidPropertyTypeException("JDBCPropertySet doesn't support this type yet."); } } rs.close(); ps.close(); } catch (SQLException e) { throw new PropertyException(e.getMessage()); } catch (NumberFormatException e) { throw new PropertyException(e.getMessage()); } finally { closeConnection(conn); } return o; }
From source file:com.gdcn.modules.db.jdbc.processor.CamelBeanProcessor.java
/** * Convert a <code>ResultSet</code> column into an object. Simple * implementations could just call <code>rs.getObject(index)</code> while * more complex implementations could perform type manipulation to match * the column's type to the bean property type. * * <p>//from w w w . jav a 2 s . co m * This implementation calls the appropriate <code>ResultSet</code> getter * method for the given property type to perform the type conversion. If * the property type doesn't match one of the supported * <code>ResultSet</code> types, <code>getObject</code> is called. * </p> * * @param rs The <code>ResultSet</code> currently being processed. It is * positioned on a valid row before being passed into this method. * * @param index The current column index being processed. * * @param propType The bean property type that this column needs to be * converted into. * * @throws SQLException if a database access error occurs * * @return The object from the <code>ResultSet</code> at the given column * index after optional type processing or <code>null</code> if the column * value was SQL NULL. */ protected Object processColumn(ResultSet rs, int index, Class<?> propType) throws SQLException { if (!propType.isPrimitive() && rs.getObject(index) == null) { return null; } if (propType.equals(String.class)) { return rs.getString(index); } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) { return Integer.valueOf(rs.getInt(index)); } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) { return Boolean.valueOf(rs.getBoolean(index)); } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) { return Long.valueOf(rs.getLong(index)); } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) { return Double.valueOf(rs.getDouble(index)); } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) { return Float.valueOf(rs.getFloat(index)); } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) { return Short.valueOf(rs.getShort(index)); } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) { return Byte.valueOf(rs.getByte(index)); } else if (propType.equals(Timestamp.class)) { return rs.getTimestamp(index); } else if (propType.equals(SQLXML.class)) { return rs.getSQLXML(index); } else { return rs.getObject(index); } }
From source file:fll.web.report.PerformanceScoreDump.java
/** * Write out the data./* ww w . j ava 2s.c o m*/ * * @param connection where to get the data from * @param tournamentID which tournament * @param csv where to write * @throws SQLException problem talking to the database */ private void writeData(final Connection connection, final int tournamentID, final CSVWriter csv) throws SQLException { PreparedStatement getScores = null; ResultSet scores = null; try { getScores = connection.prepareStatement( "SELECT Teams.TeamName, Performance.TeamNumber, Performance.RunNumber, Performance.ComputedTotal"// + ", TournamentTeams.event_division, TournamentTeams.judging_station" // + " FROM Teams, Performance, TournamentTeams" // + " WHERE Teams.TeamNumber = Performance.TeamNumber" // + " AND Teams.TeamNumber = TournamentTeams.TeamNumber" + " AND Performance.Tournament = TournamentTeams.Tournament" // + " AND Performance.Tournament = ?" // + " AND Performance.verified = TRUE" // + " AND Performance.Bye = FALSE"); getScores.setInt(1, tournamentID); scores = getScores.executeQuery(); while (scores.next()) { final String teamName = scores.getString(1); final int teamNumber = scores.getInt(2); final int runNumber = scores.getInt(3); final double score = scores.getDouble(4); final String eventDivision = scores.getString(5); final String judgingStation = scores.getString(6); final String[] row = new String[] { Integer.toString(teamNumber), teamName, Integer.toString(runNumber), Utilities.NUMBER_FORMAT_INSTANCE.format(score), eventDivision, judgingStation }; csv.writeNext(row); } } finally { SQLFunctions.close(scores); SQLFunctions.close(getScores); } }
From source file:com.sfs.whichdoctor.analysis.FinancialSummaryAnalysisDAOImpl.java
/** * Load transaction./* w w w . ja va 2 s .c o m*/ * * @param rs the rs * @param loadDetails the load details * * @return the transaction summary bean * * @throws SQLException the SQL exception */ private TransactionSummaryBean loadTransaction(final ResultSet rs, final BuilderBean loadDetails) throws SQLException { TransactionSummaryBean transaction = new TransactionSummaryBean(); transaction.setSummaryId(rs.getInt("SummaryId")); transaction.setId(rs.getInt("Id")); transaction.setType(rs.getString("Name")); transaction.setFinancialType(rs.getString("Class")); transaction.setSecurity(rs.getString("Security")); transaction.setCategory(rs.getString("Object")); transaction.setAbbreviation(rs.getString("Abbreviation")); transaction.setNumber(rs.getString("Number")); transaction.setDescription(rs.getString("Description")); transaction.setValue(rs.getDouble("Value")); transaction.setNetValue(rs.getDouble("NetValue")); transaction.setCancelled(rs.getBoolean("Cancelled")); transaction.setPersonId(rs.getInt("PersonId")); transaction.setOrganisationId(rs.getInt("OrganisationId")); try { transaction.setIssued(rs.getDate("Issued")); } catch (SQLException sqe) { dataLogger.debug("Error parsing Issued: " + sqe.getMessage()); } if (loadDetails.getBoolean("LOAD_OBJECTS")) { if (transaction.getPersonId() > 0) { try { transaction.setPerson(this.personDAO.loadGUID(transaction.getPersonId())); } catch (Exception e) { dataLogger.error("Error loading person: " + e.getMessage()); } } if (transaction.getOrganisationId() > 0) { try { transaction.setOrganisation(this.organisationDAO.loadGUID(transaction.getOrganisationId())); } catch (Exception e) { dataLogger.error("Error loading organisation: " + e.getMessage()); } } } return transaction; }