List of usage examples for java.sql ResultSet getMetaData
ResultSetMetaData getMetaData() throws SQLException;
ResultSet
object's columns. From source file:hydrograph.ui.dataviewer.adapters.DataViewerAdapter.java
private void initializeColumnCount(ResultSet resultSet) throws SQLException { columnCount = resultSet.getMetaData().getColumnCount(); }
From source file:Statement.Statement.java
private void loadView() { fieldData = new Vector<>(); fieldNames = new Vector(); //Display Revenue try {//from w w w. ja v a 2 s . c o m PreparedStatement st = cnn .prepareStatement("SELECT TypeName,Quantity FROM Revenue where ShopID = ? and Date = ?"); st.setString(1, code); st.setString(2, date); ResultSet rs = st.executeQuery(); ResultSetMetaData meta = rs.getMetaData(); for (int i = 1; i <= meta.getColumnCount(); i++) { fieldNames.add(meta.getColumnName(i)); } while (rs.next()) { Vector tmp = new Vector(); tmp.add(rs.getString(1)); tmp.add(rs.getInt(2)); fieldData.add(tmp); } model = new DefaultTableModel(fieldData, fieldNames); tbl.setModel(model); } catch (Exception e) { } }
From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java
public List<String> toStringList(ResultSet rs) throws Exception { List<String> list = new ArrayList<String>(); try {//from ww w . ja v a 2 s . c o m // we will need the column names, this will save the table meta-data like column nmae. java.sql.ResultSetMetaData rsmd = rs.getMetaData(); //loop through the ResultSet while (rs.next()) { //figure out how many columns there are int numColumns = rsmd.getColumnCount(); //each row in the ResultSet will be converted to a JSON Object StringBuilder builder = new StringBuilder(); // loop through all the columns and place them into the JSON Object for (int i = 1; i < numColumns + 1; i++) { String column_name = rsmd.getColumnName(i); if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) { builder.append(rs.getArray(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { builder.append(rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { builder.append(rs.getBoolean(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) { builder.append(rs.getBlob(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { builder.append(rs.getDouble(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { builder.append(rs.getFloat(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) { builder.append(rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { builder.append(rs.getNString(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) { // temp = rs.getString(column_name); //saving column data to temp variable // temp = ESAPI.encoder().canonicalize(temp); //decoding data to base state // temp = ESAPI.encoder().encodeForHTML(temp); //encoding to be browser safe // obj.put(column_name, temp); //putting data into JSON object // builder.append(rs.getNString(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { builder.append(rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { builder.append(rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { builder.append(rs.getDate(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) { builder.append(rs.getTime(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { builder.append(rs.getTimestamp(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) { builder.append(rs.getBigDecimal(column_name)); } else { builder.append(rs.getObject(column_name)); } } //end foreach list.add(builder.toString()); } //end while } catch (Exception e) { e.printStackTrace(); } return list; //return String list }
From source file:com.streamsets.pipeline.stage.origin.jdbc.JdbcSource.java
private void validateResultSetMetadata(List<ConfigIssue> issues, Source.Context context, ResultSet rs) { Set<String> allTables = new HashSet<>(); try {/*from w ww . ja v a 2 s. co m*/ Set<String> columnLabels = new HashSet<>(); ResultSetMetaData metadata = rs.getMetaData(); int columnIdx = metadata.getColumnCount() + 1; while (--columnIdx > 0) { String columnLabel = metadata.getColumnLabel(columnIdx); if (columnLabels.contains(columnLabel)) { issues.add( context.createConfigIssue(Groups.JDBC.name(), QUERY, JdbcErrors.JDBC_31, columnLabel)); } else { columnLabels.add(columnLabel); } allTables.add(metadata.getTableName(columnIdx)); } if (!StringUtils.isEmpty(offsetColumn) && offsetColumn.contains(".")) { issues.add(context.createConfigIssue(Groups.JDBC.name(), OFFSET_COLUMN, JdbcErrors.JDBC_32, offsetColumn)); } else { rs.findColumn(offsetColumn); } } catch (SQLException e) { // Log a warning instead of an error because some implementations such as Oracle have implicit // "columns" such as ROWNUM that won't appear as part of the result set. LOG.warn(JdbcErrors.JDBC_33.getMessage(), offsetColumn, query); LOG.warn(jdbcUtil.formatSqlException(e)); } tableNames = StringUtils.join(allTables, ", "); }
From source file:com.tascape.reactor.report.MySqlBaseBean.java
public void importJson(JSONObject json) throws NamingException, SQLException { JSONObject sr = json.getJSONObject("suite_result"); String srid = sr.getString(SuiteResult.SUITE_RESULT_ID); LOG.debug("srid {}", srid); try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + SuiteResult.TABLE_NAME + " WHERE " + SuiteResult.SUITE_RESULT_ID + " = ?;"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setString(1, srid);// w w w. j a v a 2 s .c o m ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); if (rs.first()) { LOG.debug("already imported {}", srid); return; } rs.moveToInsertRow(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); rs.updateObject(cn, sr.opt(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); LOG.debug("sr imported"); } try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + SuiteProperty.TABLE_NAME + " WHERE " + SuiteProperty.SUITE_RESULT_ID + " = ?;"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setString(1, srid); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); JSONArray sps = sr.getJSONArray("suite_properties"); int len = sps.length(); for (int i = 0; i < len; i++) { rs.moveToInsertRow(); JSONObject tr = sps.getJSONObject(i); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); if (SuiteProperty.SUITE_PROPERTY_ID.equals(cn)) { continue; } rs.updateObject(cn, tr.get(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); } LOG.debug("sps imported"); } JSONArray trs = sr.getJSONArray("case_results"); int len = trs.length(); try (Connection conn = this.getConnection()) { String sql = String.format("SELECT * FROM %s WHERE %s=? AND %s=? AND %s=? AND %s=? AND %s=?;", TaskCase.TABLE_NAME, TaskCase.SUITE_CLASS, TaskCase.CASE_CLASS, TaskCase.CASE_METHOD, TaskCase.CASE_DATA_INFO, TaskCase.CASE_DATA); PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setMaxRows(1); for (int i = 0; i < len; i++) { JSONObject tr = trs.getJSONObject(i); stmt.setString(1, tr.getString(TaskCase.SUITE_CLASS)); stmt.setString(2, tr.getString(TaskCase.CASE_CLASS)); stmt.setString(3, tr.getString(TaskCase.CASE_METHOD)); stmt.setString(4, tr.getString(TaskCase.CASE_DATA_INFO)); stmt.setString(5, tr.getString(TaskCase.CASE_DATA)); ResultSet rs = stmt.executeQuery(); if (!rs.first()) { rs.moveToInsertRow(); rs.updateString(TaskCase.SUITE_CLASS, tr.getString(TaskCase.SUITE_CLASS)); rs.updateString(TaskCase.CASE_CLASS, tr.getString(TaskCase.CASE_CLASS)); rs.updateString(TaskCase.CASE_METHOD, tr.getString(TaskCase.CASE_METHOD)); rs.updateString(TaskCase.CASE_DATA_INFO, tr.getString(TaskCase.CASE_DATA_INFO)); rs.updateString(TaskCase.CASE_DATA, tr.getString(TaskCase.CASE_DATA)); rs.insertRow(); rs.last(); rs.updateRow(); rs = stmt.executeQuery(); rs.first(); } tr.put(TaskCase.TASK_CASE_ID, rs.getLong(TaskCase.TASK_CASE_ID)); } LOG.debug("tcid updated"); } try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + CaseResult.TABLE_NAME + " WHERE " + CaseResult.SUITE_RESULT + " = ?;"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setString(1, srid); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < len; i++) { rs.moveToInsertRow(); JSONObject tr = trs.getJSONObject(i); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); rs.updateObject(cn, tr.opt(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); } LOG.debug("crs imported"); } try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + CaseResultMetric.TABLE_NAME + ";"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setMaxRows(1); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < len; i++) { JSONArray jarr = trs.getJSONObject(i).optJSONArray("CASE_result_metrics"); if (jarr == null) { continue; } int l = jarr.length(); for (int j = 0; j < l; j++) { JSONObject trm = jarr.getJSONObject(j); rs.moveToInsertRow(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); if (cn.equals(CaseResultMetric.CASE_RESULT_METRIC_ID)) { continue; } rs.updateObject(cn, trm.get(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); } } LOG.debug("crms imported"); } }
From source file:com.groupon.odo.proxylib.SQLService.java
/** * Gets the first row for a query/* w w w . j ava2s. c o m*/ * * @param query * @return result or NULL */ public HashMap<String, Object> getFirstResult(String query) throws Exception { HashMap<String, Object> result = null; Statement queryStatement = null; ResultSet results = null; try (Connection sqlConnection = getConnection()) { queryStatement = sqlConnection.createStatement(); results = queryStatement.executeQuery(query); if (results.next()) { result = new HashMap<String, Object>(); String[] columns = getColumnNames(results.getMetaData()); for (String column : columns) { result.put(column, results.getObject(column)); } } } catch (Exception e) { } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (queryStatement != null) { queryStatement.close(); } } catch (Exception e) { } } return result; }
From source file:madgik.exareme.master.queryProcessor.analyzer.stat.Stat.java
@Override public Map<String, Table> extractStats() throws Exception { DatabaseMetaData dbmd = con.getMetaData(); // dtabase metadata object // listing tables and columns String catalog = null;//w ww . java2 s . c o m String schemaPattern = null; String tableNamePattern = null; String[] types = null; String columnNamePattern = null; ResultSet resultTables = dbmd.getTables(catalog, schemaPattern, tableNamePattern, types); log.debug("Starting extracting stats"); while (resultTables.next()) { Map<String, Column> columnMap = new HashMap<String, Column>(); String tableName = StringEscapeUtils.escapeJava(resultTables.getString(3)); log.debug("Analyzing table " + tableName); int columnCount = resultTables.getMetaData().getColumnCount(); int toupleSize = 0; // in bytes tableNamePattern = tableName; ResultSet resultColumns = dbmd.getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern); int count = OptiqueAnalyzer.getCountFor(tableName, sch); if (count == 0) { log.debug("Empty table"); continue; } while (resultColumns.next()) { String columnName = StringEscapeUtils.escapeJava(resultColumns.getString(4)); int columnType = resultColumns.getInt(5); // computing column's size in bytes int columnSize = computeColumnSize(columnName, columnType, tableName); toupleSize += columnSize; // execute queries for numberOfDiffValues, minVal, maxVal Map<String, Integer> diffValFreqMap = new HashMap<String, Integer>(); // computing column's min and max values MinMax mm = computeMinMax(tableName, columnName); String minVal = mm.getMin(); String maxVal = mm.getMax(); // / List<ValFreq> freqs = computeDistinctValuesFrequency(tableName, columnName); for (ValFreq k : freqs) { diffValFreqMap.put(k.getVal(), k.getFreq()); } // /add min max diff vals in the sampling values int minOcc = computeValOccurences(tableName, columnName, minVal); if (!diffValFreqMap.containsKey(minVal)) diffValFreqMap.put(minVal, minOcc); int maxOcc = computeValOccurences(tableName, columnName, maxVal); if (!diffValFreqMap.containsKey(maxVal)) diffValFreqMap.put(maxVal, maxOcc); int diffVals = diffValFreqMap.size(); Column c = new Column(columnName, columnType, columnSize, diffVals, minVal, maxVal, diffValFreqMap); columnMap.put(columnName, c); } ResultSet pkrs = dbmd.getExportedKeys("", "", tableName); String pkey = "DEFAULT_KEY"; while (pkrs.next()) { pkey = pkrs.getString("PKCOLUMN_NAME"); break; } Table t = new Table(tableName, columnCount, toupleSize, columnMap, count, pkey); schema.put(tableName, t); } return schema; }
From source file:computer_store.GUI.java
/** * Takes a JTable and a ResultSet as parameters and populates the JTable with the supplied ResultSet * @param table//w w w . ja va 2 s . com * @param rs */ private void fillTable(javax.swing.JTable table, java.sql.ResultSet rs) { try { //To remove previously added rows while (table.getRowCount() > 0) { ((javax.swing.table.DefaultTableModel) table.getModel()).removeRow(0); } int columns = rs.getMetaData().getColumnCount(); Object[] ids = new Object[columns]; while (rs.next()) { Object[] row = new Object[columns]; for (int i = 1; i <= columns; i++) { row[i - 1] = rs.getObject(i); } ((javax.swing.table.DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row); } for (int i = 1; i <= columns; i++) { ids[i - 1] = rs.getMetaData().getColumnName(i); } ((javax.swing.table.DefaultTableModel) table.getModel()).setColumnIdentifiers(ids); rs.close(); } catch (Exception e) { System.out.print(e); } }
From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java
/** * Verify that even with an empty ResultSet; the resultset meta-data can still * be queried. Previously, this was <i>Issue 75</i>. *///from www. j a va 2 s.c om @Test public void testEmptyResultSet() throws Exception { Statement stmt = con.createStatement(); String truncate = "TRUNCATE regressiontest;"; stmt.execute(truncate); String select = "select ivalue from " + TABLE; ResultSet result = stmt.executeQuery(select); assertFalse("Make sure we have no rows", result.next()); ResultSetMetaData rsmd = result.getMetaData(); assertTrue("Make sure we do get a result", rsmd.getColumnDisplaySize(1) != 0); assertNotNull("Make sure we do get a label", rsmd.getColumnLabel(1)); System.out.println( "Found a column in ResultsetMetaData even when there are no rows: " + rsmd.getColumnLabel(1)); stmt.close(); }
From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java
/** * Create a column group and confirm that the {@code ResultSetMetaData} works. *//* ww w . j av a 2s. c o m*/ @Test public void testResultSetMetaData() throws Exception { Statement stmt = con.createStatement(); // Create the target Column family String createCF = "CREATE COLUMNFAMILY t33 (k int PRIMARY KEY," + "c text " + ") ;"; stmt.execute(createCF); stmt.close(); con.close(); // open it up again to see the new CF con = DriverManager .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS)); // paraphrase of the snippet from the ISSUE #33 provided test PreparedStatement statement = con.prepareStatement("update t33 set c=? where k=123"); statement.setString(1, "mark"); statement.executeUpdate(); ResultSet result = statement.executeQuery("SELECT k, c FROM t33;"); ResultSetMetaData metadata = result.getMetaData(); int colCount = metadata.getColumnCount(); System.out.println("Test Issue #33"); DatabaseMetaData md = con.getMetaData(); System.out.println(); System.out.println("--------------"); System.out.println("Driver Version : " + md.getDriverVersion()); System.out.println("DB Version : " + md.getDatabaseProductVersion()); System.out.println("Catalog term : " + md.getCatalogTerm()); System.out.println("Catalog : " + con.getCatalog()); System.out.println("Schema term : " + md.getSchemaTerm()); System.out.println("--------------"); while (result.next()) { metadata = result.getMetaData(); colCount = metadata.getColumnCount(); assertEquals("Total column count should match schema for t33", 2, metadata.getColumnCount()); System.out.printf("(%d) ", result.getRow()); for (int i = 1; i <= colCount; i++) { System.out.print(showColumn(i, result) + " "); switch (i) { case 1: assertEquals("First Column: k", "k", metadata.getColumnName(1)); assertEquals("First Column Type: int", Types.INTEGER, metadata.getColumnType(1)); break; case 2: assertEquals("Second Column: c", "c", metadata.getColumnName(2)); assertEquals("Second Column Type: text", Types.NVARCHAR, metadata.getColumnType(2)); break; } } System.out.println(); } }