List of usage examples for java.sql ResultSet getMetaData
ResultSetMetaData getMetaData() throws SQLException;
ResultSet
object's columns. From source file:fabrice.CSVPrinter.java
/** * Prints all the objects in the given JDBC result set. * * @param resultSet//from w ww .ja v a 2 s. c om * result set the values to print. * @throws IOException * If an I/O error occurs * @throws SQLException * if a database access error occurs */ public void printRecords(final ResultSet resultSet) throws SQLException, IOException { final int columnCount = resultSet.getMetaData().getColumnCount(); while (resultSet.next()) { for (int i = 1; i <= columnCount; i++) { print(resultSet.getObject(i)); } println(); } }
From source file:com.stratelia.webactiv.util.DBUtil.java
/** * Gets all table names.//from www . jav a2 s .co m * @return */ public static Set<String> getAllTableNames() { Connection privateConnection = null; ResultSet tables_rs = null; boolean testingMode = false; Set<String> tableNames = new LinkedHashSet<String>(); try { // On ne peux pas utiliser une simple connection du pool // on utilise une connection extrieure au contexte transactionnel des ejb synchronized (DBUtil.class) { if (getInstance().connectionForTest != null) { privateConnection = getInstance().connectionForTest; testingMode = true; } else { privateConnection = ConnectionPool.getConnection(); } } DatabaseMetaData dbMetaData = privateConnection.getMetaData(); tables_rs = dbMetaData.getTables(null, null, null, null); tables_rs.getMetaData(); while (tables_rs.next()) { tableNames.add(tables_rs.getString(TABLE_NAME)); } } catch (Exception e) { SilverTrace.debug("util", "DBUtil.getAllTableNames", "database error ...", e); } finally { close(tables_rs); if (privateConnection != null && !testingMode) { close(privateConnection); } } return tableNames; }
From source file:com.hangum.tadpole.engine.sql.util.executer.procedure.ProcedureExecutor.java
/** * cursor? ?.//w ww.j a v a2 s. c om * * @param rs * @throws Exception */ protected void setResultCursor(String reqQuery, ResultSet rs) throws Exception { Map<Integer, String> mapColumns = ResultSetUtils.getColumnName(rs); Map<Integer, String> mapTableColum = ResultSetUtils.getColumnTableName(userDB, rs); Map<Integer, Integer> mapColumnType = ResultSetUtils.getColumnType(rs.getMetaData()); TadpoleResultSet sourceDataList = ResultSetUtils.getResultToList(rs, 1000); ResultSetUtilDTO resultSet = new ResultSetUtilDTO( // PublicTadpoleDefine.SQL_STATEMENTS_TYPE.PROCEDURE, userDB, reqQuery, mapColumns, mapTableColum, mapColumnType, sourceDataList); addResultDAO(resultSet); }
From source file:BQJDBC.QueryResultTest.Timeouttest.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 {//from w w w .j a va 2s .co m Result = Timeouttest.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.gdo.project.util.SqlUtils.java
@Deprecated public static InputStream e4xFacet(StclContext stclContext, String query) { if (StringUtils.isEmpty(query)) { if (getLog().isWarnEnabled()) { getLog().warn(stclContext, "SqlUtils:e4xFacet empty query..."); }/*from w ww . j a v a2 s . c o m*/ return StringHelper.EMPTY_STRING_INPUT_STREAM; } try { PreparedStatement stmt = SqlUtils.prepareStatement(stclContext, query); ResultSet rs = SqlUtils.preparedSelect(stmt); if (rs != null) { StringBuffer e4x = new StringBuffer(); e4x.append("<records>"); while (rs.next()) { e4x.append(" <record>\n"); int cols = rs.getMetaData().getColumnCount(); for (int j = 1; j <= cols; j++) { String tag = rs.getMetaData().getColumnName(j); String tag1 = new String(tag.getBytes(), "UTF-8"); // db // connection String value = rs.getString(j); String value1 = new String(value.getBytes(), "ISO-8859-1"); // db // value e4x.append(String.format(" <%1$s>%2$s</%1$s>\n", tag1, value1)); } e4x.append(" </record>\n"); } e4x.append("</records>\n"); return new ByteArrayInputStream(e4x.toString().getBytes()); } } catch (SQLException e) { if (getLog().isWarnEnabled()) { getLog().warn(stclContext, "SqlUtils:e4xFacet error", e); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return StringHelper.EMPTY_STRING_INPUT_STREAM; }
From source file:teambootje.A9.java
/** * Creates new form A9//from www . j a v a 2 s . co m */ public A9() { initComponents(); setLocationRelativeTo(null); setLayout(new BorderLayout()); //Create and set up the window. setTitle("SS Rotterdam Analyse || Analyse 9"); ImageIcon icon = new ImageIcon("img/bootje.jpg"); setIconImage(icon.getImage()); // back BTN JButton back = new JButton("Back"); add(back, BorderLayout.NORTH); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); // panel en Label JPanel ana = new JPanel(); add(ana, BorderLayout.CENTER); //tabel String sql = "SELECT persoon.Name, COUNT(post) AS Aantal FROM persoon, posts WHERE persoon.AID = posts.AID GROUP BY persoon.Name"; List<Object[]> list = new ArrayList<Object[]>(); ResultSet rs = null; try { rs = db.runSql(sql); while (rs.next()) { String name = rs.getString("persoon.Name"); int amount = rs.getInt("Aantal"); String[] row = new String[rs.getMetaData().getColumnCount()]; for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { row[i - 1] = rs.getString(i); } list.add(row); //chart JButton chart = new JButton("Chart"); add(chart, BorderLayout.SOUTH); chart.addActionListener(new ActionListener() { String n1 = name; int a1 = amount; @Override public void actionPerformed(ActionEvent e) { DefaultPieDataset pieDataset = new DefaultPieDataset(); pieDataset.setValue(n1, a1); pieDataset.setValue("WestCordHotels", new Integer(1)); pieDataset.setValue("Voetbalr", new Integer(2)); pieDataset.setValue("VeraBauman", new Integer(1)); pieDataset.setValue("TonWesselink", new Integer(2)); pieDataset.setValue("Stoomschip Rotterdam", new Integer(25)); pieDataset.setValue("shirleys86", new Integer(2)); pieDataset.setValue("SevereWeather_N", new Integer(2)); pieDataset.setValue("SalvatoreOrtisi", new Integer(4)); pieDataset.setValue("RuudvEck", new Integer(2)); pieDataset.setValue("RuudvandenBos", new Integer(1)); pieDataset.setValue("Roffa85", new Integer(1)); pieDataset.setValue("RichardPh0t0", new Integer(2)); pieDataset.setValue("RebekkaKadijk", new Integer(2)); pieDataset.setValue("ray_rademaker", new Integer(6)); pieDataset.setValue("PoushNL", new Integer(1)); pieDataset.setValue("popupsquare", new Integer(2)); pieDataset.setValue("Plan_78", new Integer(3)); pieDataset.setValue("Petrahoogenboom", new Integer(1)); pieDataset.setValue("PatriciaBenard", new Integer(2)); pieDataset.setValue("OVKatendrecht", new Integer(2)); pieDataset.setValue("OdileHemmen", new Integer(2)); pieDataset.setValue("NLMaritiem", new Integer(2)); pieDataset.setValue("Nellyvdvlies", new Integer(1)); pieDataset.setValue("meerkatting", new Integer(2)); pieDataset.setValue("MeerkatsNow", new Integer(2)); pieDataset.setValue("marygoossens1", new Integer(1)); pieDataset.setValue("MarjoleinNagel", new Integer(1)); pieDataset.setValue("MaaikeMaasdijk", new Integer(1)); pieDataset.setValue("KidsErOpUit", new Integer(2)); pieDataset.setValue("Katendrechtnr1", new Integer(25)); pieDataset.setValue("jpsoree", new Integer(2)); pieDataset.setValue("JolandaBolscher", new Integer(2)); pieDataset.setValue("jes4life", new Integer(1)); pieDataset.setValue("JaccoScheer", new Integer(1)); pieDataset.setValue("GwNpop", new Integer(2)); pieDataset.setValue("Gerarddegraaff", new Integer(1)); pieDataset.setValue("FR12Patrick", new Integer(3)); pieDataset.setValue("FlorentinaNow", new Integer(1)); pieDataset.setValue("FIVBWorldChamps", new Integer(2)); pieDataset.setValue("FIVBVolleyball", new Integer(2)); pieDataset.setValue("FeestdjNik", new Integer(1)); pieDataset.setValue("ensanne", new Integer(1)); pieDataset.setValue("elsekramer", new Integer(1)); pieDataset.setValue("EelcoBeijl", new Integer(1)); pieDataset.setValue("EdwindeKoning1", new Integer(2)); pieDataset.setValue("DMiddelman", new Integer(3)); pieDataset.setValue("de_rotterdam", new Integer(2)); pieDataset.setValue("CvanAdrighem", new Integer(2)); pieDataset.setValue("carolinedejager", new Integer(1)); pieDataset.setValue("CaatVanEnst", new Integer(1)); pieDataset.setValue("BotlekBusiness", new Integer(2)); pieDataset.setValue("AnneWallisDeVri", new Integer(2)); pieDataset.setValue("010byday", new Integer(4)); JFreeChart chart = ChartFactory.createPieChart3D("Aantal posts per personen", pieDataset, true, true, true); PiePlot3D p = (PiePlot3D) chart.getPlot(); //p.setForegroundAlpha(TOP_ALIGNMENT); ChartFrame pie = new ChartFrame("Aantal posts per personen", chart); pie.setVisible(true); pie.setSize(500, 500); pie.setLocationRelativeTo(null); //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, e); } Object[][] array = new Object[list.size()][]; Object columnNames[] = { "Naam", "Aantal" }; list.toArray(array); JTable table = new JTable(array, columnNames); JScrollPane scroll = new JScrollPane(table); scroll.setPreferredSize(new Dimension(400, 400)); ana.add(scroll); }
From source file:com.tonbeller.jpivot.mondrian.ScriptableMondrianDrillThroughTableModel.java
/** * execute sql query/*from ww w . j ava 2 s. c om*/ * @throws Exception */ private void executeQuery() { Connection con = null; try { InputStream catExtIs = ScriptableMondrianDrillThroughTableModel.class.getClassLoader() .getResourceAsStream("/" + catalogExtension); Digester catExtDigester = new Digester(); catExtDigester.push(this); catExtDigester.addSetProperties("extension"); catExtDigester.addObjectCreate("extension/script", "com.tonbeller.jpivot.mondrian.script.ScriptColumn"); catExtDigester.addSetProperties("extension/script"); catExtDigester.addSetNext("extension/script", "addScript"); catExtDigester.parse(catExtIs); URL scriptsBaseURL = Thread.currentThread().getContextClassLoader().getResource(scriptRootUrl); scriptEngine = new GroovyScriptEngine(new URL[] { scriptsBaseURL }); con = getConnection(); Statement s = con.createStatement(); s.setMaxRows(maxResults); ResultSet rs = s.executeQuery(sql); ResultSetMetaData md = rs.getMetaData(); int numCols = md.getColumnCount(); List columnTitlesList = new ArrayList(); // set column headings for (int i = 0; i < numCols; i++) { // columns are 1 based columnTitlesList.add(i, md.getColumnName(i + 1)); } // loop on script columns for (ListIterator sIt = scripts.listIterator(); sIt.hasNext();) { final ScriptColumn sc = (ScriptColumn) sIt.next(); columnTitlesList.add(sc.getPosition() - 1, sc.getTitle()); } columnTitles = (String[]) columnTitlesList.toArray(new String[0]); // loop through rows List tempRows = new ArrayList(); Map scriptInput = new HashMap(); Binding binding = new Binding(); while (rs.next()) { List rowList = new ArrayList(); scriptInput.clear(); // loop on columns, 1 based for (int i = 0; i < numCols; i++) { rowList.add(i, rs.getObject(i + 1)); scriptInput.put(columnTitles[i], rs.getObject(i + 1)); } binding.setVariable("input", scriptInput); // loop on script columns for (ListIterator sIt = scripts.listIterator(); sIt.hasNext();) { final ScriptColumn sc = (ScriptColumn) sIt.next(); scriptEngine.run(sc.getFile(), binding); final Object output = binding.getVariable("output"); if (output instanceof Map) { Map outMap = (Map) output; rowList.add(sc.getPosition() - 1, new DefaultCell((String) outMap.get("URL"), (String) outMap.get("Value"))); } else if (output instanceof String) { rowList.add(sc.getPosition() - 1, (String) output); } else { throw new Exception("Unknown groovy script return type (not a Map nor String)."); } } tempRows.add(new DefaultTableRow(rowList.toArray())); } rs.close(); rows = (TableRow[]) tempRows.toArray(new TableRow[0]); } catch (Exception e) { e.printStackTrace(); logger.error("?", e); // problem occured, set table model to zero size rows = new TableRow[1]; columnTitles = new String[1]; columnTitles[0] = "An error occured"; Object[] row = new Object[1]; row[0] = e.toString(); rows[0] = new DefaultTableRow(row); ready = false; return; } finally { try { con.close(); } catch (Exception e1) { // ignore } } ready = true; }
From source file:azkaban.jobtype.ReportalTeradataRunner.java
private void outputQueryResult(ResultSet result, OutputStream outputStream) throws SQLException { final PrintStream outFile = new PrintStream(outputStream); final String delim = ","; boolean isHeaderPending = true; if (result != null) { while (result.next()) { int numColumns = result.getMetaData().getColumnCount(); StringBuilder dataString = new StringBuilder(); if (isHeaderPending) { StringBuilder headerString = new StringBuilder(); for (int j = 1; j <= numColumns; j++) { String colName = formatValue(result.getMetaData().getColumnName(j)); if (j > 1) { headerString.append(delim).append(colName); } else { headerString.append(colName); }/*from ww w. ja v a2s . co m*/ } isHeaderPending = false; outFile.println(headerString.toString()); } for (int j = 1; j <= numColumns; j++) { String colVal = result.getString(j); if (colVal == null) { colVal = "\"null\""; } else { colVal = formatValue(colVal); } if (j > 1) { dataString.append(delim).append(colVal); } else { dataString.append(colVal); } } outFile.println(dataString.toString()); } } outFile.close(); }
From source file:com.tonbeller.jpivot.mondrian.script.ScriptableMondrianDrillThroughTableModel.java
/** * execute sql query//from w w w . j a va2s . com * @throws Exception */ private void executeQuery() { Connection con = null; try { InputStream catExtIs = ScriptableMondrianDrillThroughTableModel.class.getClassLoader() .getResourceAsStream("/" + catalogExtension); if (catExtIs != null) { Digester catExtDigester = new Digester(); catExtDigester.push(this); catExtDigester.addSetProperties("extension"); catExtDigester.addObjectCreate("extension/script", "com.tonbeller.jpivot.mondrian.script.ScriptColumn"); catExtDigester.addSetProperties("extension/script"); catExtDigester.addSetNext("extension/script", "addScript"); catExtDigester.parse(catExtIs); URL scriptsBaseURL = Thread.currentThread().getContextClassLoader().getResource(scriptRootUrl); scriptEngine = new GroovyScriptEngine(new URL[] { scriptsBaseURL }); } con = getConnection(); Statement s = con.createStatement(); s.setMaxRows(maxResults); ResultSet rs = s.executeQuery(sql); ResultSetMetaData md = rs.getMetaData(); int numCols = md.getColumnCount(); List columnTitlesList = new ArrayList(); // set column headings for (int i = 0; i < numCols; i++) { // columns are 1 based columnTitlesList.add(i, md.getColumnName(i + 1)); } // loop on script columns for (ListIterator sIt = scripts.listIterator(); sIt.hasNext();) { final ScriptColumn sc = (ScriptColumn) sIt.next(); columnTitlesList.add(sc.getPosition() - 1, sc.getTitle()); } columnTitles = (String[]) columnTitlesList.toArray(new String[0]); // loop through rows List tempRows = new ArrayList(); Map scriptInput = new HashMap(); Binding binding = new Binding(); while (rs.next()) { List rowList = new ArrayList(); scriptInput.clear(); // loop on columns, 1 based for (int i = 0; i < numCols; i++) { rowList.add(i, rs.getObject(i + 1)); scriptInput.put(columnTitles[i], rs.getObject(i + 1)); } binding.setVariable("input", scriptInput); // loop on script columns for (ListIterator sIt = scripts.listIterator(); sIt.hasNext();) { final ScriptColumn sc = (ScriptColumn) sIt.next(); scriptEngine.run(sc.getFile(), binding); final Object output = binding.getVariable("output"); if (output instanceof Map) { Map outMap = (Map) output; rowList.add(sc.getPosition() - 1, new DefaultCell((String) outMap.get("URL"), (String) outMap.get("Value"))); } else if (output instanceof String) { rowList.add(sc.getPosition() - 1, (String) output); } else { throw new Exception("Unknown groovy script return type (not a Map nor String)."); } } tempRows.add(new DefaultTableRow(rowList.toArray())); } rs.close(); rows = (TableRow[]) tempRows.toArray(new TableRow[0]); } catch (Exception e) { e.printStackTrace(); logger.error("?", e); // problem occured, set table model to zero size rows = new TableRow[1]; columnTitles = new String[1]; columnTitles[0] = "An error occured"; Object[] row = new Object[1]; row[0] = e.toString(); rows[0] = new DefaultTableRow(row); ready = false; return; } finally { try { con.close(); } catch (Exception e1) { // ignore } } ready = true; }
From source file:SeeAccount.java
public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { PrintWriter out = null;//from ww w . ja va2s . co m Connection connection = null; Statement statement = null; ResultSet rs; try { outResponse.setContentType("text/html"); out = outResponse.getWriter(); Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB"); connection = ds.getConnection(); statement = connection.createStatement(); rs = statement.executeQuery("SELECT * FROM acc_acc"); ResultSetMetaData md = rs.getMetaData(); out.println("<HTML><HEAD><TITLE> Thumbnail Identification Record</TITLE></HEAD>"); out.println("<BODY>"); out.println("Account Information:<BR>"); out.println("<table>"); out.println("<tr><td>"); for (int i = 1; i <= md.getColumnCount(); i++) { out.println("Column #" + i + "<BR>"); out.println("getColumnName : " + md.getColumnName(i) + "<BR>"); out.println("getColumnClassName : " + md.getColumnClassName(i) + "<BR>"); out.println("getColumnDisplaySize : " + md.getColumnDisplaySize(i) + "<BR>"); out.println("getColumnType : " + md.getColumnType(i) + "<BR>"); out.println("getTableName : " + md.getTableName(i) + "<BR>"); out.println("<HR>"); } out.println("</BODY></HTML>"); } catch (Exception e) { e.printStackTrace(); } }