List of usage examples for java.sql ResultSetMetaData getColumnCount
int getColumnCount() throws SQLException;
ResultSet
object. From source file:cosmos.sql.TestSql.java
@Test public void testConjunction() throws SQLException { loadDriverClass();/* w ww. j a v a2s.c om*/ Connection connection = null; Statement statement = null; try { Properties info = new Properties(); info.put("url", JDBC_URL); info.put("user", USER); info.put("password", PASSWORD); connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info); statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("select \"PAGE_ID\" from \"" + CosmosDriver.COSMOS + "\".\"" + meataData.uuid() + "\" where PAGE_ID='9' and REVISION_ID='9'"); final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); assertEquals(columnCount, 1); int resultsFound = 0; while (resultSet.next()) { assertEquals(metaData.getColumnName(1), "PAGE_ID"); @SuppressWarnings("unchecked") List<Entry<Column, RecordValue<?>>> sValues = (List<Entry<Column, RecordValue<?>>>) resultSet .getObject("PAGE_ID"); assertEquals(sValues.size(), 1); RecordValue<?> onlyValue = sValues.iterator().next().getValue(); assertEquals(onlyValue.visibility().toString(), "[en]"); assertEquals(onlyValue.value(), Integer.valueOf(9).toString()); resultsFound++; break; } assertEquals(resultsFound, 1); } finally { close(connection, statement); } }
From source file:hw.java
public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); Vector<String> columnNames = new Vector<String>(); int columnCount = metaData.getColumnCount(); for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); }/*ww w . j a v a2 s .c o m*/ Vector<Vector<Object>> data = new Vector<Vector<Object>>(); while (rs.next()) { Vector<Object> vector = new Vector<Object>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(rs.getObject(columnIndex)); } data.add(vector); } return new DefaultTableModel(data, columnNames); }
From source file:cosmos.sql.TestSql.java
@Test public void testNoLimit() throws SQLException { loadDriverClass();/* w w w . j ava 2 s.c om*/ Connection connection = null; Statement statement = null; try { Properties info = new Properties(); info.put("url", JDBC_URL); info.put("user", USER); info.put("password", PASSWORD); connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info); statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery( "select \"PAGE_ID\" from \"" + CosmosDriver.COSMOS + "\".\"" + meataData.uuid() + "\""); final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); assertEquals(columnCount, 1); int resultsFound = 0; SortedSet<String> sets = Sets.newTreeSet(); for (int i = 0; i < 10; i++) { sets.add(Integer.valueOf(i).toString()); } Queue<String> values = Lists.newLinkedList(sets); while (resultSet.next()) { assertEquals(metaData.getColumnName(1), "PAGE_ID"); @SuppressWarnings("unchecked") List<Entry<Column, RecordValue<?>>> sValues = (List<Entry<Column, RecordValue<?>>>) resultSet .getObject("PAGE_ID"); assertEquals(sValues.size(), 1); RecordValue<?> onlyValue = sValues.iterator().next().getValue(); assertEquals(onlyValue.visibility().toString(), "[en]"); values.remove(onlyValue.value()); resultsFound++; } assertEquals(resultsFound, 10); assertEquals(values.size(), 0); } finally { close(connection, statement); } }
From source file:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java
@Override public List<Row> executeQuery(final String user, final String password, final String db, final String query) throws BackendException { Statement st = null;//from ww w. jav a 2 s . c om Connection conn = null; ResultSet rs = null; List<Row> result = new LinkedList<Row>(); try { conn = this.connectToDB(user, password, db); st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); this.logString(query.trim(), user); rs = st.executeQuery(query.trim()); while (rs.next()) { Row row = new PostgresRow(); ResultSetMetaData metaData = rs.getMetaData(); for (int i = 1; i <= metaData.getColumnCount(); i++) { row.getFields().add(rs.getObject(i)); row.getFieldsByName().put(metaData.getColumnName(i), rs.getObject(i)); } result.add(row); } } catch (SQLException e) { throw new BackendException(e); } catch (ClassNotFoundException e) { throw new BackendException(e); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(st); DbUtils.closeQuietly(conn); } return result; }
From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java
protected Integer searchColumnByName(String name) throws SQLException { Integer columnIndex = null;// w w w.j a v a2s . c om ResultSetMetaData metadata = resultSet.getMetaData(); for (int i = 1; i <= metadata.getColumnCount(); i++) { String columnName = metadata.getColumnName(i); if (name.equalsIgnoreCase(columnName)) { columnIndex = i; break; } } return columnIndex; }
From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java
protected Integer searchColumnByLabel(String label) throws SQLException { Integer columnIndex = null;//from w w w . j a va2 s . co m ResultSetMetaData metadata = resultSet.getMetaData(); for (int i = 1; i <= metadata.getColumnCount(); i++) { String columnLabel = metadata.getColumnLabel(i); if (columnLabel != null && label.equalsIgnoreCase(columnLabel)) { columnIndex = i; break; } } return columnIndex; }
From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java
/** * Similar to the same method in original pubtest utility, but doesn't throw an exception if 0 rows are returned * and uses existing(established) JDBC connection corresponding to its published datasource name. * // w w w . jav a2 s . co m * @param item * * @return result - A string containing a formatted response with the rows and first row latency: <rows>:<firstRowLatency> */ public static String executeQuery(RegressionItem item, HashMap<String, Connection> cisConnections, String outputFile, String delimiter, String printOutputType) throws CompositeException { // Set the command and action name String command = "executeQuery"; String actionName = "REGRESSION_TEST"; int rows = 0; String result = null; Connection conn = null; Statement stmt = null; ResultSet rs = null; start = System.currentTimeMillis(); long firstRowLatency = 0L; // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { try { conn = getJdbcConnection(item.database, cisConnections); // don't need to check for null here. String URL = null; String userName = null; if (conn.getMetaData() != null) { if (conn.getMetaData().getURL() != null) URL = conn.getMetaData().getURL(); if (conn.getMetaData().getUserName() != null) userName = conn.getMetaData().getUserName(); } RegressionManagerUtils.printOutputStr(printOutputType, "debug", "RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delimiter, printOutputType). item.database=" + item.database + " cisConnections.URL=" + URL + " cisConnections.userName=" + userName + " outputFile=" + outputFile + " delimiter=" + delimiter + " printOutputType=" + printOutputType, ""); RegressionManagerUtils.printOutputStr(printOutputType, "debug", "DEBUG: connection to DB successful", ""); stmt = conn.createStatement(); stmt.execute(item.input.replaceAll("\n", " ")); rs = stmt.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData(); int columns = rsmd.getColumnCount(); RegressionManagerUtils.printOutputStr(printOutputType, "debug", "DEBUG: number metadata columns=" + columns, ""); // Get the column metadata boolean addSep = false; String content = ""; RegressionManagerUtils.printOutputStr(printOutputType, "debug", "DEBUG: Get column metadata.", ""); for (int i = 0; i < columns; i++) { if (addSep) { content += delimiter; } if (rsmd.getColumnName(i + 1) != null) content += rsmd.getColumnName(i + 1).toString(); else content += ""; addSep = true; } if (outputFile != null) CommonUtils.appendContentToFile(outputFile, content); RegressionManagerUtils.printOutputStr(printOutputType, "results", content, ""); // Read the values boolean firstRow = true; RegressionManagerUtils.printOutputStr(printOutputType, "debug", "DEBUG: Begin Query Loop.", ""); while (rs.next()) { if (firstRow) { firstRowLatency = System.currentTimeMillis() - start; firstRow = false; RegressionManagerUtils.printOutputStr(printOutputType, "debug", "DEBUG: Set first row latency time=" + firstRowLatency, ""); } addSep = false; content = ""; for (int i = 0; i < columns; i++) { if (addSep) { content += delimiter; } if (rs.getObject(i + 1) != null) content += rs.getObject(i + 1).toString(); else content += ""; addSep = true; } if (outputFile != null) CommonUtils.appendContentToFile(outputFile, content); RegressionManagerUtils.printOutputStr(printOutputType, "results", content, ""); rows++; } } catch (SQLException e) { RegressionManagerUtils.printOutputStr(printOutputType, "debug", "DEBUG: Exception caught in RegressionManagerUtils.executeQuery:", ""); RegressionManagerUtils.printOutputStr(printOutputType, "debug", e.getMessage(), ""); throw new CompositeException("executeQuery(): " + e.getMessage()); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { rs = null; stmt = null; throw new CompositeException( "executeQuery(): unable to close ResultSet or Statement" + e.getMessage()); } } RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeQuery()", ""); } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } // <rows>:<firstRowLatency> result = "" + rows + ":" + firstRowLatency; return result; /* Note: to process this result string on the client invocation side use the following pattern: * * String result = RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delim, printOutputType, "results"); String results[] = result.split(":"); if (results.length > 1) { rowCount = Integer.valueOf(results[0]); firstRowLatency.addAndGet(Long.parseLong(results[1])); } */ }
From source file:com.tascape.reactor.report.MySqlBaseBean.java
public List<Map<String, Object>> dumpResultSetToList(ResultSet rs) throws SQLException { List<Map<String, Object>> rsml = new ArrayList<>(); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { Map<String, Object> d = new LinkedHashMap<>(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { d.put(rsmd.getColumnLabel(col), rs.getObject(col)); }/*from w w w .j a v a 2s.co m*/ rsml.add(d); } LOG.trace("{} rows loaded", rsml.size()); return rsml; }
From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java
private JSONArray toJSONArray(ResultSet rs, JSONArray json) throws Exception { String temp = null;//from w w w . j a va2s. c o m try { // 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 JSONObject obj = new JSONObject(); // 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) { obj.put(column_name, rs.getArray(column_name).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { obj.put(column_name, rs.getBigDecimal(column_name).toBigInteger().toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { obj.put(column_name, ((Boolean) rs.getBoolean(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) { obj.put(column_name, rs.getBlob(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { obj.put(column_name, ((Double) rs.getDouble(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { obj.put(column_name, ((Float) rs.getFloat(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) { obj.put(column_name, ((Integer) rs.getInt(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { obj.put(column_name, 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 // obj.put(column_name, rs.getNString(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { obj.put(column_name, ((Integer) rs.getInt(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { obj.put(column_name, ((Integer) rs.getInt(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { obj.put(column_name, rs.getDate(column_name).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) { obj.put(column_name, TimeStampUtils.dateTimeToString(rs.getTime(column_name))); } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { obj.put(column_name, TimeStampUtils.timeStampToString(rs.getTimestamp(column_name))); } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) { obj.put(column_name, rs.getBigDecimal(column_name).toString()); } else { obj.put(column_name, rs.getObject(column_name)); } } //end foreach json.add(obj); } //end while } catch (Exception e) { e.printStackTrace(); } return json; //return JSON array }
From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java
/** * Verify that the driver navigates a resultset according to the JDBC rules. * In all cases, the resultset should be pointing to the first record, which can * be read without invoking {@code next()}. * @throws Exception Fatal error.//from w w w. j a va 2 s. c o m */ @Test public void testResultSetNavigation() throws Exception { Statement statement = con.createStatement(); String truncate = "TRUNCATE regressiontest;"; statement.execute(truncate); String insert1 = "INSERT INTO regressiontest (keyname,bValue,iValue) VALUES( 'key0',true, 2000);"; statement.executeUpdate(insert1); String insert2 = "INSERT INTO regressiontest (keyname,bValue) VALUES( 'key1',false);"; statement.executeUpdate(insert2); String select = "SELECT * from regressiontest;"; ResultSet result = statement.executeQuery(select); ResultSetMetaData metadata = result.getMetaData(); int colCount = metadata.getColumnCount(); System.out.println("Before doing a next()"); System.out.printf("(%d) ", result.getRow()); for (int i = 1; i <= colCount; i++) { System.out.print(showColumn(i, result) + " "); } System.out.println(); System.out.println("Fetching each row with a next()"); while (result.next()) { metadata = result.getMetaData(); colCount = metadata.getColumnCount(); System.out.printf("(%d) ", result.getRow()); for (int i = 1; i <= colCount; i++) { System.out.print(showColumn(i, result) + " "); } System.out.println(); } }