List of usage examples for java.sql ResultSet getMetaData
ResultSetMetaData getMetaData() throws SQLException;
ResultSet
object's columns. From source file:org.tradex.jdbc.JDBCHelper.java
/** * Executes the passed SQL and returns the resulting rows maps of values keyed by column name within a map keyed by rownumber (starting with zero) * @param sql The SQL to execute/* w ww .ja v a2 s . c o m*/ * @return the results */ public Map<Integer, Map<String, Object>> result(CharSequence sql) { Map<Integer, Map<String, Object>> results = new TreeMap<Integer, Map<String, Object>>(); Map<Integer, String> colNumToName; Connection conn = null; PreparedStatement ps = null; ResultSet rset = null; try { conn = ds.getConnection(); ps = conn.prepareStatement(sql.toString()); rset = ps.executeQuery(); int colCount = rset.getMetaData().getColumnCount(); colNumToName = new HashMap<Integer, String>(colCount); ResultSetMetaData rsmd = rset.getMetaData(); for (int i = 1; i <= colCount; i++) { colNumToName.put(i, rsmd.getColumnLabel(i)); } int rowNum = 0; while (rset.next()) { Map<String, Object> row = new HashMap<String, Object>(colCount); results.put(rowNum, row); for (int i = 1; i <= colCount; i++) { row.put(colNumToName.get(i), rset.getObject(i)); } rowNum++; } return results; } catch (Exception e) { throw new RuntimeException("Query for [" + sql + "] failed", e); } finally { try { rset.close(); } catch (Exception e) { } try { ps.close(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } }
From source file:BQJDBC.QueryResultTest.QueryResultTest.java
@Test public void QueryResultTest05() { final String sql = "SELECT word FROM publicdata:samples.shakespeare WHERE word='huzzah' ;"; final String description = "The word \"huzzah\" NOTE: It doesn't appear in any any book, so it returns with a null #WHERE"; this.logger.info("Test number: 05"); this.logger.info("Running query:" + sql); java.sql.ResultSet Result = null; try {// ww w .j a v a2 s . c o m Result = QueryResultTest.con.createStatement().executeQuery(sql); this.logger.debug(Result.getMetaData().getColumnCount()); } catch (SQLException e) { this.logger.error("SQLexception" + e.toString()); Assert.fail("SQLException" + e.toString()); } Assert.assertNotNull(Result); this.logger.debug(description); try { if (Result.getType() != ResultSet.TYPE_FORWARD_ONLY) Assert.assertFalse(Result.first()); } catch (SQLException e) { this.logger.error("SQLexception" + e.toString()); Assert.fail(e.toString()); } }
From source file:com.kylinolap.query.test.KylinTestBase.java
protected int output(ResultSet resultSet, boolean needDisplay) throws SQLException { int count = 0; ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); StringBuilder sb = new StringBuilder("\n"); if (needDisplay) { for (int i = 1; i <= columnCount; i++) { sb.append(metaData.getColumnName(i)); sb.append("-"); sb.append(metaData.getTableName(i)); sb.append("-"); sb.append(metaData.getColumnTypeName(i)); if (i < columnCount) { sb.append("\t"); } else { sb.append("\n"); }// ww w . jav a 2 s .c o m } } while (resultSet.next()) { if (needDisplay) { for (int i = 1; i <= columnCount; i++) { sb.append(resultSet.getString(i)); if (i < columnCount) { sb.append("\t"); } else { sb.append("\n"); } } } count++; } printInfo(sb.toString()); return count; }
From source file:com.adaptris.core.services.jdbc.JdbcDataCaptureServiceImpl.java
protected void saveKeys(AdaptrisMessage msg, Statement stmt) throws SQLException { ResultSet rs = null; Statement savedKeysQuery = null; try {/*from ww w . j a v a 2 s . co m*/ if (saveReturnedKeys()) { if (!actor.isOldJbc()) { rs = stmt.getGeneratedKeys(); rs.next(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { String name = rsmd.getColumnName(i); String value = rs.getObject(name).toString(); msg.addMetadata(name, value); } } else { savedKeysQuery = createStatement(actor.getSqlConnection()); rs = savedKeysQuery.executeQuery( "select max(" + saveReturnedKeysColumn + ") from " + saveReturnedKeysTable + ";"); rs.next(); String value = rs.getObject(saveReturnedKeysColumn).toString(); msg.addMetadata(saveReturnedKeysColumn, value); } } } finally { JdbcUtil.closeQuietly(savedKeysQuery); JdbcUtil.closeQuietly(rs); } }
From source file:com.mmnaseri.dragonfly.fluent.impl.AbstractSelectQueryFinalizer.java
private <H> List<Map<Mapping, Object>> execute(SelectQueryExecution<E, H> selection) { final Connection connection = session.getConnection(); final PreparedStatement preparedStatement; try {// w w w.jav a 2 s. c o m final String sql = selection.getSql() + ";"; LogFactory.getLog(Statement.class).info("Preparing statement: " + sql); preparedStatement = connection.prepareStatement(sql); } catch (SQLException e) { throw new DatabaseNegotiationException("Failed to get a prepared statement from the database", e); } for (ParameterDescriptor descriptor : selection.getParameters()) { try { if (descriptor.getValue() == null) { preparedStatement.setNull(descriptor.getIndex(), descriptor.getSqlType()); } else { preparedStatement.setObject(descriptor.getIndex(), descriptor.getValue()); } } catch (SQLException e) { throw new StatementPreparationException( "Failed to prepare statement for parameter " + descriptor.getIndex(), e); } } final ResultSet resultSet; final ResultSetMetaData metaData; try { resultSet = preparedStatement.executeQuery(); } catch (SQLException e) { throw new DatabaseNegotiationException("Failed to retrieve the results from the data source", e); } try { metaData = resultSet.getMetaData(); } catch (SQLException e) { throw new DatabaseNegotiationException("Failed to get result set metadata for query", e); } final ArrayList<Map<Mapping, Object>> result = new ArrayList<Map<Mapping, Object>>(); while (true) { try { if (!resultSet.next()) { break; } final HashMap<Mapping, Object> map = new HashMap<Mapping, Object>(); for (int i = 1; i <= metaData.getColumnCount(); i++) { map.put(new ImmutableMapping(metaData.getTableName(i), metaData.getColumnName(i), metaData.getColumnLabel(i)), resultSet.getObject(i)); } result.add(map); } catch (SQLException e) { throw new DatabaseNegotiationException("Failed to get the next row", e); } } return result; }
From source file:com.redsqirl.workflow.server.connect.jdbc.JdbcStoreConnection.java
public List<String> displaySelect(ResultSet rs, int maxToRead) throws SQLException { int colNb = 0; List<Integer> sizes = new LinkedList<Integer>(); List<List<String>> cells = new LinkedList<List<String>>(); int sizeCol = 0; colNb = rs.getMetaData().getColumnCount(); {/*from w ww . java 2s . c o m*/ // Set column names List<String> row = new LinkedList<String>(); for (int i = 1; i <= colNb; ++i) { row.add(rs.getMetaData().getColumnName(i)); sizeCol = rs.getMetaData().getColumnName(i).length(); sizes.add(sizeCol); } cells.add(row); } while (rs.next()) { List<String> row = new LinkedList<String>(); for (int i = 1; i <= colNb; ++i) { String colVal = rs.getString(i); row.add(colVal); sizeCol = 0; if (colVal != null) { sizeCol = colVal.length(); } if (sizes.get(i - 1) < sizeCol) { sizes.set(i - 1, sizeCol); } } cells.add(row); } cleanOldStatement(rs); // logger.info("displaySelect list size" + sizes.size() + " " + // ans.size()); List<String> ans = new LinkedList<String>(); for (int i = 0; i < cells.size(); i++) { List<String> row = cells.get(i); String rowStr = "|"; for (int j = 0; j < row.size(); j++) { String aux = row.get(j); if (aux == null) { aux = "null"; } rowStr += StringUtils.rightPad(aux, sizes.get(j)) + "|"; } // logger.info("displaySelect -" + newLine + "-"); ans.add(rowStr); } String tableLine = "+"; for (int j = 0; j < sizes.size(); j++) { tableLine += StringUtils.rightPad("", sizes.get(j), "-") + "+"; } if (ans.size() > 0) { ans.add(1, tableLine); } ans.add(0, tableLine); if (ans.size() < maxToRead) { ans.add(ans.size(), tableLine); } return ans; }
From source file:at.ac.tuwien.inso.subcat.reporter.Reporter.java
private void exportWordStats(final ExporterConfig config, Project project, int commitDictId, int bugDictId, Settings settings, final ReportWriter formatter, String outputPath, Map<String, Object> vars) throws SQLException, Exception { formatter.init(project, settings, outputPath); model.rawForeach(config.getQuery(), vars, new ResultCallback() { @Override/*from w ww .java2 s. c o m*/ public void processResult(ResultSet res) throws SemanticException, SQLException, Exception { ResultSetMetaData meta = res.getMetaData(); String[] titles = new String[meta.getColumnCount()]; if (titles.length != 2) { throw new SemanticException( "semantic error: invalid column count, expected: (<string>, <string>)", config.getStart(), config.getEnd()); } if (meta.getColumnType(1) != Types.VARCHAR || meta.getColumnType(2) != Types.VARCHAR) { throw new SemanticException( "semantic error: invalid column type, expected: (<string>, <string>), got " + "(<" + meta.getColumnTypeName(1) + ">, <" + meta.getColumnTypeName(2) + ">)", config.getStart(), config.getEnd()); } Map<String, Map<String, Integer>> data = new HashMap<String, Map<String, Integer>>(); Lemmatizer lemmatiser = new Lemmatizer(); Set<String> categoryNames = new HashSet<String>(); while (res.next()) { String category = res.getString(1); categoryNames.add(category); List<String> lemma = lemmatiser.lemmatize(res.getString(2)); for (String word : lemma) { Map<String, Integer> counter = data.get(word); if (counter == null) { counter = new HashMap<String, Integer>(); data.put(word, counter); } Integer wordCount = counter.get(category); if (wordCount == null) { wordCount = 0; } counter.put(category, wordCount + 1); } } String[] header = new String[categoryNames.size() + 1]; header[0] = "word"; int i = 1; for (String catName : categoryNames) { header[i] = catName; i++; } formatter.writeHeader(header); for (Entry<String, Map<String, Integer>> entry : data.entrySet()) { Map<String, Integer> scores = entry.getValue(); String[] row = new String[header.length]; row[0] = entry.getKey(); i = 1; for (String cat : categoryNames) { Integer score = scores.get(cat); if (score == null) { score = 0; } row[i] = score.toString(); i++; } formatter.writeSet(row); } formatter.writeFooter(header); } }); }
From source file:com.espertech.esper.epl.db.DatabasePollingViewableFactory.java
private static QueryMetaData getExampleQueryMetaData(Connection connection, String[] parameters, String sampleSQL, ColumnSettings metadataSetting, boolean isUsingMetadataSQL) throws ExprValidationException { // Simply add up all input parameters List<String> inputParameters = new LinkedList<String>(); inputParameters.addAll(Arrays.asList(parameters)); Statement statement;// ww w. j a v a 2 s. com try { statement = connection.createStatement(); } catch (SQLException ex) { String text = "Error creating statement"; log.error(text, ex); throw new ExprValidationException(text + ", reason: " + ex.getMessage()); } ResultSet result = null; try { result = statement.executeQuery(sampleSQL); } catch (SQLException ex) { try { statement.close(); } catch (SQLException e) { log.info("Error closing statement: " + e.getMessage(), e); } String text; if (isUsingMetadataSQL) { text = "Error compiling metadata SQL to retrieve statement metadata, using sql text '" + sampleSQL + "'"; } else { text = "Error compiling metadata SQL to retrieve statement metadata, consider using the 'metadatasql' syntax, using sql text '" + sampleSQL + "'"; } log.error(text, ex); throw new ExprValidationException(text + ", reason: " + ex.getMessage()); } Map<String, DBOutputTypeDesc> outputProperties; try { outputProperties = compileResultMetaData(result.getMetaData(), metadataSetting); } catch (SQLException ex) { try { result.close(); } catch (SQLException e) { // don't handle } try { statement.close(); } catch (SQLException e) { // don't handle } String text = "Error in statement '" + sampleSQL + "', failed to obtain result metadata"; log.error(text, ex); throw new ExprValidationException(text + ", please check the statement, reason: " + ex.getMessage()); } finally { if (result != null) { try { result.close(); } catch (SQLException e) { log.warn("Exception closing result set: " + e.getMessage()); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { log.warn("Exception closing result set: " + e.getMessage()); } } } return new QueryMetaData(inputParameters, outputProperties); }
From source file:hmp.HMPClassiferSummary.java
private void run(String[] args) throws ClassNotFoundException, FileNotFoundException, SQLException, IOException, ParseException { /*/*w ww .jav a 2 s . c o m*/ * Get command line options */ cli = getOptions(args); /* * Determine if rdp results is file or directory */ File rdpFile = new File(cli.getOptionValue("rdpDir")); boolean isDirectory = false; if (rdpFile.isDirectory()) { isDirectory = true; } /* * Setup database connections * */ MySQLConnector connector = new MySQLConnector("localhost", "biosql", "biosql", "biosql"); conn = connector.getConnection(); connector = new MySQLConnector("localhost", cli.getOptionValue("db"), cli.getOptionValue("dbUser"), cli.getOptionValue("dbPassword")); microbiome = connector.getConnection(); /* * create output directory */ createOutputDir("summary"); /* * Determine which columns are available for rdp levels */ rdpLevelCols = new ArrayList<String>(); ResultSet rsCol = microbiome.createStatement().executeQuery("select * from rdp_result_data limit 10"); ResultSetMetaData rsMeta = rsCol.getMetaData(); int colNumber = rsMeta.getColumnCount(); for (int i = 1; i < colNumber + 1; i++) { rdpLevelCols.add(rsMeta.getColumnName(i)); } /* * process file/files */ PrintWriter writer = new PrintWriter(new FileWriter("summary_all.txt")); writer.println("sampleid|level|taxa|count|len|sd|gc|sd|skew"); if (isDirectory) { File[] files = getFiles(rdpFile); int count = 0; for (int i = 0; i < files.length; i++) { if (count >= 0) { System.out.println("===PROCESSING FILE " + i + " ==="); processReads(files[i], writer); count++; } } } else { processReads(rdpFile, writer); } writer.close(); System.out.println("Done!"); }
From source file:org.dcm4chee.dashboard.ui.report.display.DisplayReportDiagramPanel.java
@Override public void onBeforeRender() { super.onBeforeRender(); Connection jdbcConnection = null; try {/*ww w . j a v a 2s .c om*/ 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) { } } }