List of usage examples for java.sql ResultSet getObject
Object getObject(String columnLabel) throws SQLException;
Gets the value of the designated column in the current row of this ResultSet
object as an Object
in the Java programming language.
From source file:com.streamsets.pipeline.stage.it.KeywordsInObjectNamesIT.java
@Test public void testKeywordInPartitionColumnName() throws Exception { executeUpdate(Utils.format("CREATE DATABASE IF NOT EXISTS `{}`", keyword)); HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder() .partitions(new PartitionConfigBuilder().addPartition(keyword, HiveType.STRING, "value").build()) .build();// w w w .j a v a 2s . c om HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build(); Map<String, Field> map = new LinkedHashMap<>(); map.put("col", Field.create("value")); Record record = RecordCreator.create("s", "s:1"); record.set(Field.create(map)); try { processRecords(processor, hiveTarget, ImmutableList.of(record)); } catch (StageException se) { LOG.error("Processing exception", se); Assert.fail("Processing testing record unexpectedly failed: " + se.getMessage()); throw se; } assertTableExists("default.tbl"); assertQueryResult("select * from tbl", new QueryValidator() { @Override public void validateResultSet(ResultSet rs) throws Exception { assertResultSetStructure(rs, new ImmutablePair("tbl.col", Types.VARCHAR), new ImmutablePair(Utils.format("tbl.{}", keyword), Types.VARCHAR)); Assert.assertTrue("Table tbl doesn't contain any rows", rs.next()); Assert.assertEquals("value", rs.getObject(1)); Assert.assertEquals("value", rs.getObject(2)); Assert.assertFalse("Table tbl contains more then one row", rs.next()); } }); }
From source file:edu.stanford.junction.sample.sql.QueryHandler.java
@Override public void onMessageReceived(MessageHeader header, JSONObject message) { //String query = q.getQueryText(); String query = message.optString("query"); query = query.toLowerCase();//from w w w .j a v a 2s .c o m if (!query.contains("select")) return; if (query.contains("drop") || query.contains("delete")) return; System.out.println("Got query: " + query); Connection connection = null; try { // Load the JDBC driver String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver Class.forName(driverName); // Create a connection to the database //String serverName = "192.168.1.122"; String serverName = "127.0.0.1"; String mydatabase = "jinzora3"; String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url String username = "jinzora"; String password = "jinzora"; connection = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { // Could not find the database driver e.printStackTrace(); } catch (SQLException e) { // Could not connect to the database e.printStackTrace(); } try { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(query); ResultSetMetaData rsMetaData = rs.getMetaData(); int cols = rsMetaData.getColumnCount(); while (rs.next()) { JSONObject row = new JSONObject(); try { for (int i = 1; i <= cols; i++) { // stupid indexing row.put(rsMetaData.getColumnName(i), rs.getObject(i)); } } catch (JSONException e) { e.printStackTrace(); } System.out.println("sending " + row); if (mActor != null) { //mActor.getJunction().sendMessageToTarget(header.getReplyTarget(),row); header.getReplyTarget().sendMessage(row); } } } catch (SQLException e) { e.printStackTrace(); } System.out.println("closing stream."); //results.close(); }
From source file:org.paxml.tag.sql.DdlTag.java
private String getVersion(String version, Context context) { if (isQuery(version)) { Object result = executeSql(version, context); if (result instanceof List) { List list = (List) result; if (list.isEmpty()) { throw new PaxmlRuntimeException("No ddl version value can be found with query: " + version); }/*from w ww . j av a 2 s .c o m*/ Map row = (Map) list.get(0); return row.values().iterator().next().toString(); } else if (result instanceof ResultSet) { ResultSet rs = (ResultSet) result; try { if (rs.next()) { return rs.getObject(1).toString(); } else { throw new PaxmlRuntimeException("No ddl version value can be found with query: " + version); } } catch (SQLException e) { throw new PaxmlRuntimeException("Cannot get ddl version value with query: " + version, e); } } else { throw new PaxmlRuntimeException("Unknown ddl version query result: " + result); } } else { return version; } }
From source file:org.wte4j.impl.service.SimpleDbViewModelService.java
@Override public WteDataModel createModel(Template<?> template, Object input) { String viewName = template.getProperties().get(VIEW_NAME); String pkColumnName = template.getProperties().get(PRIMARY_KEY_COLUMN_NAME); Integer pk = (Integer) input; Map<String, Object> dataMap = new HashMap<String, Object>(); //TODO PreparedStatement! String query = "select * from " + viewName + " where " + pkColumnName + "=" + pk; try {//from w ww . ja v a2s . co m Connection connection = null; Statement statement = null; try { connection = ds.getConnection(); statement = connection.createStatement(); ResultSet rs = statement.executeQuery(query); ResultSetMetaData metaData = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= metaData.getColumnCount(); i++) { String columnName = metaData.getColumnName(i).toLowerCase(); dataMap.put(columnName, rs.getObject(i)); } } } finally { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } } catch (SQLException e) { throw new WteException("error in createModel (" + viewName + ", " + pkColumnName + ", " + pk + ")", e); } return new WteMapModel(dataMap); }
From source file:it.smartcommunitylab.aac.model.ClientDetailsRowMapper.java
public ClientDetails mapRow(ResultSet rs, int rowNum) throws SQLException { BaseClientDetails details = new BaseClientDetails(rs.getString("client_id"), rs.getString("resource_ids"), rs.getString("scope"), rs.getString("authorized_grant_types"), rs.getString("authorities"), rs.getString("web_server_redirect_uri")); details.setClientSecret(rs.getString("client_secret")); if (rs.getObject("access_token_validity") != null) { details.setAccessTokenValiditySeconds(rs.getInt("access_token_validity")); }//from ww w . jav a2s . c om if (rs.getObject("refresh_token_validity") != null) { details.setRefreshTokenValiditySeconds(rs.getInt("refresh_token_validity")); } String json = rs.getString("additional_information"); if (json != null) { try { @SuppressWarnings("unchecked") Map<String, Object> additionalInformation = mapper.readValue(json, Map.class); details.setAdditionalInformation(additionalInformation); } catch (Exception e) { logger.warn("Could not decode JSON for additional information: " + details, e); } } else { details.setAdditionalInformation(new HashMap<String, Object>()); } // merge developer roles into authorities it.smartcommunitylab.aac.model.User developer = userRepository.findOne(rs.getLong("developerId")); if (developer != null) { List<GrantedAuthority> list = new LinkedList<GrantedAuthority>(); if (details.getAuthorities() != null) list.addAll(details.getAuthorities()); list.addAll(developer.getRoles().stream().filter(r -> !StringUtils.isEmpty(r.getContext())) .collect(Collectors.toList())); details.setAuthorities(list); } return details; }
From source file:Professor.java
public void checkData(String sql) throws Exception { ResultSet rs = st.executeQuery(sql); ResultSetMetaData metadata = rs.getMetaData(); for (int i = 0; i < metadata.getColumnCount(); i++) { System.out.print("\t"+ metadata.getColumnLabel(i + 1)); }/* ww w . ja v a 2s. com*/ System.out.println("\n----------------------------------"); while (rs.next()) { for (int i = 0; i < metadata.getColumnCount(); i++) { Object value = rs.getObject(i + 1); if (value == null) { System.out.print("\t "); } else { System.out.print("\t"+value.toString().trim()); } } System.out.println(""); } }
From source file:com.zimbra.cs.db.JdbcClient.java
private Object[] getCurrentRow(ResultSet rs) throws SQLException { ResultSetMetaData md = rs.getMetaData(); int colCount = md.getColumnCount(); Object[] row = new Object[colCount]; for (int i = 0; i < colCount; i++) { row[i] = rs.getObject(i + 1); }/*from ww w.ja va 2 s .c om*/ return row; }
From source file:com.tesora.dve.sql.util.JdbcConnectionResourceResponse.java
private List<ResultRow> convertNativeResults(ResultSet mrs) throws Throwable { ResultSetMetaData rsmd = mrs.getMetaData(); ArrayList<ResultRow> converted = new ArrayList<ResultRow>(); while (mrs.next()) { ResultRow rr = new ResultRow(); for (int i = 0; i < rsmd.getColumnCount(); i++) { rr.addResultColumn(mrs.getObject(i + 1), mrs.wasNull()); }//from w ww . j a va 2 s . c o m converted.add(rr); } return converted; }
From source file:com.github.tosdan.utils.sql.BasicRowProcessorMod.java
/** * Convert a <code>ResultSet</code> row into a <code>Map</code>. This * implementation returns a <code>Map</code> with case insensitive column * names as keys. Calls to <code>map.get("COL")</code> and * <code>map.get("col")</code> return the same value. * @see org.apache.commons.dbutils.RowProcessor#toMap(java.sql.ResultSet) * @param rs ResultSet that supplies the map data * @throws SQLException if a database access error occurs * @return the newly created Map//from w ww . jav a2 s .c om */ @Override public Map<String, Object> toMap(ResultSet rs) throws SQLException { Map<String, Object> result = new LinkedHashMap<String, Object>(); ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); for (int i = 1; i <= cols; i++) { Object obj = rs.getObject(i); result.put(rsmd.getColumnName(i), obj); } return result; }
From source file:com.fmguler.ven.QueryMapper.java
protected void mapRecursively(ResultSet rs, Set columns, String tableName, Class objectClass, List parentList) { try {//from w w w .j a v a 2 s.co m if (!columns.contains(tableName + "_id")) return; //this object does not exist in the columns Object id = rs.getObject(tableName + "_id"); if (id == null) return; //this object exists in the columns but null, probably because of left join //create bean wrapper for the object class BeanWrapperImpl wr = new BeanWrapperImpl(objectClass); //already caches class introspection (CachedIntrospectionResults.forClass()) wr.setPropertyValue("id", id); //set the id property Object object = wr.getWrappedInstance(); boolean map = true; //check if this object exists in the parent list (since SQL joins are cartesian products, do not create new object if this row is just the same as previous) for (Iterator it = parentList.iterator(); it.hasNext();) { Object objectInList = (Object) it.next(); if (objectIdEquals(objectInList, id)) { wr.setWrappedInstance(objectInList); //already exists in the list, use that instance map = false; // and do not map again break; } } if (map) parentList.add(object); //could not find in the parent list, add the new object PropertyDescriptor[] pdArr = wr.getPropertyDescriptors(); for (int i = 0; i < pdArr.length; i++) { PropertyDescriptor pd = pdArr[i]; Class fieldClass = pd.getPropertyType(); //field class String fieldName = Convert.toDB(pd.getName()); //field name Object fieldValue = wr.getPropertyValue(pd.getName()); String columnName = tableName + "_" + fieldName; //database class (primitive property) if (map && dbClasses.contains(fieldClass)) { if (columns.contains(columnName)) { if (debug) System.out.println(">>field is found: " + columnName); wr.setPropertyValue(pd.getName(), rs.getObject(columnName)); } else { if (debug) System.out.println("--field not found: " + columnName); } continue; //if this is a primitive property, it cannot be an object or list } //many to one association (object property) if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) { if (columns.contains(columnName + "_id")) { if (debug) System.out.println(">>object is found " + columnName); List list = new ArrayList(1); //we know there will be single result if (!map) list.add(fieldValue); //otherwise we cannot catch one to many assc. (lists) of many to one (object) assc. mapRecursively(rs, columns, columnName, fieldClass, list); if (list.size() > 0) wr.setPropertyValue(pd.getName(), list.get(0)); } else { if (debug) System.out.println("--object not found: " + columnName); } } //one to many association (list property) if (fieldValue instanceof List) { //Note: here recurring row's list property is mapped and add to parent's list if (columns.contains(columnName + "_id")) { Class elementClass = VenList.findElementClass((List) fieldValue); if (debug) System.out.println(">>list is found " + columnName); mapRecursively(rs, columns, columnName, elementClass, (List) fieldValue); } else { if (debug) System.out.println("--list not found: " + columnName); } } } } catch (Exception ex) { System.out.println("Ven - error while mapping row, table: " + tableName + " object class: " + objectClass + " error: " + ex.getMessage()); if (debug) { ex.printStackTrace(); } } }