List of usage examples for java.sql ResultSet getMetaData
ResultSetMetaData getMetaData() throws SQLException;
ResultSet
object's columns. From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java
private String resultToDisplay(ResultSet result, int issue, String note) throws Exception { StringBuilder sb = new StringBuilder("Test Issue #" + issue + " - " + note + "\n"); ResultSetMetaData metadata = result.getMetaData(); int colCount = metadata.getColumnCount(); sb.append("--------------").append("\n"); while (result.next()) { metadata = result.getMetaData(); colCount = metadata.getColumnCount(); sb.append(String.format("(%d) ", result.getRow())); for (int i = 1; i <= colCount; i++) { sb.append(showColumn(i, result) + " "); }/* www .j ava 2 s . c om*/ sb.append("\n"); } return sb.toString(); }
From source file:cosmos.sql.TestSql.java
public void testDistinct() throws SQLException { loadDriverClass();/*from ww w . j a v a2 s .co m*/ 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 DISTINCT \"PAGE_ID\" from \"" + CosmosDriver.COSMOS + "\".\"" + meataData.uuid() + "\""); 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"); Object value = resultSet.getObject("PAGE_ID"); } assertEquals(resultsFound, 2); } finally { close(connection, statement); } }
From source file:cosmos.sql.TestSql.java
@Test public void testNoLimit() throws SQLException { loadDriverClass();/*from www .j a va 2 s . co m*/ 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:com.dsf.dbxtract.cdc.journal.JournalExecutor.java
private void copyResultsetToMap(ResultSet rs, List<Map<String, Object>> result) throws SQLException { if (rs == null) throw new SQLException("result is null"); if (result == null) throw new NullPointerException("result map is null"); while (rs.next()) { if (journalColumns == null) { journalColumns = new ArrayList<>(); for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { journalColumns.add(rs.getMetaData().getColumnLabel(i + 1).toLowerCase()); }//w ww .j a va2s . c om } Map<String, Object> map = new HashMap<>(); for (String col : journalColumns) { map.put(col, rs.getObject(col)); } result.add(map); } }
From source file:com.googlecode.fascinator.portal.services.impl.DatabaseServicesImpl.java
/** * Parse the results of the query into a basic Java data structure. Users * wanting the original result set should call getResultSet() directly * against the prepared statement./*from www .j a v a 2 s . com*/ * * @param sql The prepared statement to get the results from. * @return List<Map<String, String>> A list of result rows as key/value * pairs in HashMaps * @throws Exception if there is an error. */ @Override public List<Map<String, String>> getResults(PreparedStatement sql) throws Exception { // Prepare variables List<Map<String, String>> response = new ArrayList<Map<String, String>>(); ResultSet results = null; ResultSetMetaData columns = null; try { // Run the search results = sql.executeQuery(); // Process the results columns = results.getMetaData(); if (results.isClosed()) { log.error("!!! ResultSet is closed"); return response; } while (results.next()) { Map<String, String> row = new HashMap<String, String>(); for (int i = 1; i <= columns.getColumnCount(); i++) { // log.debug("getResults(): Storing '{}' ({}) => " + // results.getString(i), columns.getColumnName(i), // columns.getColumnLabel(i)); row.put(columns.getColumnName(i), results.getString(i)); } response.add(row); } // Finish up results.close(); return response; } catch (SQLException ex) { throw new Exception("Error executing query:", ex); } }
From source file:cosmos.sql.TestSql.java
@Test public void testLimit() throws SQLException { loadDriverClass();/* www . j a v a 2s . co m*/ 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() + "\" limit 2 OFFSET 0"); 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(resultsFound).toString()); resultsFound++; } assertEquals(resultsFound, 2); } finally { close(connection, statement); } }
From source file:cosmos.sql.TestSql.java
@Test public void testJoin() throws SQLException { loadDriverClass();/*from ww w .j av a 2 s. c o m*/ 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() + "\" limit 2 OFFSET 0"); 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(resultsFound).toString()); resultsFound++; } assertEquals(resultsFound, 2); } finally { close(connection, statement); } }
From source file:com.nway.spring.jdbc.bean.JavassistBeanProcessor.java
private <T> T createBeanByJavassist(ResultSet rs, Class<T> mappedClass, String key) throws SQLException { DbBeanFactory dynamicRse = DBBEANFACTORY_CACHE.get(key); // /* w ww . j a va2 s. c o m*/ if (dynamicRse != null) { return dynamicRse.createBean(rs, mappedClass); } T bean = this.newInstance(mappedClass); ResultSetMetaData rsmd = rs.getMetaData(); PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(mappedClass); int[] columnToProperty = this.mapColumnsToProperties(rsmd, props); StringBuilder handlerScript = new StringBuilder(); handlerScript.append("{").append(mappedClass.getName()).append(" bean = new ").append(mappedClass.getName()) .append("();\n"); PropertyDescriptor desc = null; for (int i = 1; i < columnToProperty.length; i++) { if (columnToProperty[i] == PROPERTY_NOT_FOUND) { continue; } desc = props[columnToProperty[i]]; Class<?> propType = desc.getPropertyType(); Object value = processColumn(rs, i, propType, desc.getWriteMethod().getName(), handlerScript); this.callSetter(bean, desc, value); } handlerScript.append("return bean;"); handlerScript.append("}"); try { ClassPool classPool = ClassPool.getDefault(); classPool.appendClassPath(new LoaderClassPath(ClassUtils.getDefaultClassLoader())); CtClass ctHandler = classPool.makeClass(DynamicClassUtils.getBeanProcessorName(mappedClass)); ctHandler.setSuperclass(classPool.get("com.nway.spring.jdbc.bean.DbBeanFactory")); CtMethod mapRow = CtNewMethod.make( "public Object createBean(java.sql.ResultSet rs, Class type) throws java.sql.SQLException{return null;}", ctHandler); mapRow.setGenericSignature("<T:Ljava/lang/Object;>(Ljava/sql/ResultSet;Ljava/lang/Class<TT;>;)TT;"); mapRow.setBody(handlerScript.toString()); ctHandler.addMethod(mapRow); DBBEANFACTORY_CACHE.put(key, (DbBeanFactory) ctHandler.toClass().newInstance()); } catch (Exception e) { throw new DynamicObjectException("javassist [ " + mappedClass.getName() + " ] ", e); } return bean; }
From source file:org.gofleet.openLS.ddbb.dao.postgis.PostGisHBGeoCodingDAO.java
@Transactional(readOnly = true) public List<AbstractResponseParametersType> reverseGeocode(final ReverseGeocodeRequestType param) { HibernateCallback<List<AbstractResponseParametersType>> action = new HibernateCallback<List<AbstractResponseParametersType>>() { public List<AbstractResponseParametersType> doInHibernate(Session session) throws HibernateException, SQLException { PositionType position = param.getPosition(); position.getPoint().getPos().getValue(); Geometry geometry = GeoUtil.getGeometry(position); List<AbstractResponseParametersType> res_ = new LinkedList<AbstractResponseParametersType>(); // TODO change deprecation? @SuppressWarnings("deprecation") CallableStatement consulta = session.connection().prepareCall("{call gls_reverse_geocoding(?)}"); PGgeometry geom = new PGgeometry(geometry.toText()); consulta.setObject(1, geom); LOG.debug(consulta);/*ww w . java2s . c om*/ ResultSet o = consulta.executeQuery(); ReverseGeocodeResponseType grt = new ReverseGeocodeResponseType(); while (o.next()) { ReverseGeocodedLocationType geocode = new ReverseGeocodedLocationType(); if (geocode.getAddress() == null) geocode.setAddress(new AddressType()); if (geocode.getAddress().getStreetAddress() == null) geocode.getAddress().setStreetAddress(new StreetAddressType()); for (int i = 1; i < o.getMetaData().getColumnCount(); i++) { String value = new String(o.getString(i).getBytes(), Charset.forName("ISO-8859-1")); if (o.getMetaData().getColumnName(i).equals("street")) { StreetNameType street = new StreetNameType(); street.setValue(value); street.setOfficialName(value); geocode.getAddress().getStreetAddress().getStreet().add(street); } else if (o.getMetaData().getColumnName(i).equals("munsub")) { NamedPlaceType place = new NamedPlaceType(); place.setValue(value); place.setType(NamedPlaceClassification.MUNICIPALITY_SUBDIVISION); geocode.getAddress().getPlace().add(place); } else if (o.getMetaData().getColumnName(i).equals("mun")) { NamedPlaceType place = new NamedPlaceType(); place.setValue(value); place.setType(NamedPlaceClassification.MUNICIPALITY); geocode.getAddress().getPlace().add(place); } else if (o.getMetaData().getColumnName(i).equals("subcountry")) { NamedPlaceType place = new NamedPlaceType(); place.setValue(value); place.setType(NamedPlaceClassification.COUNTRY_SUBDIVISION); geocode.getAddress().getPlace().add(place); } else if (o.getMetaData().getColumnName(i).equals("country")) { geocode.getAddress().setCountryCode(value); } } try { grt.getReverseGeocodedLocation().add(geocode); } catch (Throwable t) { LOG.error("Error extracting data from database.", t); } } res_.add(grt); return res_; } }; return hibernateTemplate.executeWithNativeSession(action); }