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:ResultSetIterator.java
/** * Convert a <code>ResultSet</code> row into an <code>Object[]</code>. * This implementation copies column values into the array in the same * order they're returned from the <code>ResultSet</code>. Array elements * will be set to <code>null</code> if the column was SQL NULL. * * @see org.apache.commons.dbutils.RowProcessor#toArray(java.sql.ResultSet) *//*from w w w. j av a2 s .co m*/ public Object[] toArray(ResultSet rs) throws SQLException { ResultSetMetaData meta = rs.getMetaData(); int cols = meta.getColumnCount(); Object[] result = new Object[cols]; for (int i = 0; i < cols; i++) { result[i] = rs.getObject(i + 1); } return result; }
From source file:com.netspective.axiom.policy.AnsiDatabasePolicy.java
public Object executeAndGetSingleValue(ConnectionContext cc, String sql) throws SQLException { Object value = null;/*from www. ja va 2 s .co m*/ Statement stmt = null; ResultSet rs = null; try { stmt = cc.getConnection().createStatement(); try { rs = stmt.executeQuery(sql); if (rs.next()) value = rs.getObject(1); } finally { if (rs != null) rs.close(); } } catch (NamingException e) { throw new SQLException(e.toString() + " [" + sql + "]"); } catch (SQLException e) { throw new SQLException(e.toString() + " [" + sql + "]"); } finally { if (stmt != null) stmt.close(); } return value; }
From source file:com.quangphuong.crawler.dbutil.DBWrapper.java
public List<Object> getEntitiesByCondition(Object entity) { String sql = selectAll.concat(entity.getClass().getSimpleName()); if (!"".equals(customWhereClause)) { sql = sql.concat(customWhereClause); } else {//w w w . j a va2 s . c om sql = sql.concat(whereClause); } Connection con = null; if (this.isDisconnect) { con = DBHandler.openConnection(); } List<Object> result = new ArrayList<Object>(); try { Statement statement; if (this.isDisconnect) { statement = con.createStatement(); } else { statement = connection.createStatement(); } Field[] attributes = entity.getClass().getDeclaredFields(); if ("".equals(customWhereClause)) { // Field[] attributes = entity.getClass().getDeclaredFields(); int count = 0; for (Field attribute : attributes) { attribute.setAccessible(true); if (!attribute.isAnnotationPresent(Ignore.class) && !attribute.isAnnotationPresent(AutoIncrement.class) && attribute.get(entity) != null) { String value = attribute.get(entity).toString(); if (count == 0) { sql = sql.concat(attribute.getName() + "=" + "\'" + value + "\'"); } else { sql = sql.concat(" AND " + attribute.getName() + "=" + "\'" + value + "\'"); } count++; } } } if (useDistinct) { sql = sql.concat(groupByClause.replace("@", distinctField)); } System.out.println(sql); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { List<Object> listFields = new ArrayList(); List<Class<?>> listFieldTypes = new ArrayList(); for (Field attribute : attributes) { attribute.setAccessible(true); if (!attribute.isAnnotationPresent(Ignore.class)) { Object obj = resultSet.getObject(attribute.getName()); listFields.add(obj); listFieldTypes.add(attribute.getType()); } } Object obj = entity.getClass().getConstructor((Class<?>[]) listFieldTypes.toArray(new Class[0])) .newInstance(listFields.toArray()); result.add(obj); } } catch (Exception ex) { Logger.getLogger(DBWrapper.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (this.isDisconnect && con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } return result; }
From source file:edu.ku.brc.specify.ui.db.ResultSetTableModel.java
/** * @param setter/* w ww . ja v a 2s .c o m*/ * @param parent * @param fieldName * @param fieldClass * @param resultSet * @param colIndex * @throws SQLException */ protected void setField(final DataObjectSettable setter, final Object parent, final String fieldName, final Class<?> fieldClass, final ResultSet resultSet, final int colIndex) throws SQLException { Object fieldDataObj = resultSet.getObject(colIndex + 1); //log.debug("fieldName ["+fieldName+"] fieldClass ["+fieldClass.getSimpleName()+"] colIndex [" + colIndex + "] fieldDataObj [" + fieldDataObj+"]"); if (fieldDataObj != null) { if (fieldClass == String.class) { setter.setFieldValue(parent, fieldName, fieldDataObj); } else if (fieldClass == Byte.class) { setter.setFieldValue(parent, fieldName, resultSet.getByte(colIndex + 1)); } else if (fieldClass == Short.class) { setter.setFieldValue(parent, fieldName, resultSet.getShort(colIndex + 1)); } else { setter.setFieldValue(parent, fieldName, fieldDataObj); } } }
From source file:cn.sel.dvw.SimpleObjectRowMapper.java
@Override public T mapRow(ResultSet resultSet, int rowNum) throws SQLException { T rowObj;//w w w . j ava 2 s .co m try { rowObj = clazz.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); throw new SQLException("Failed to instantiate the result object!", e); } Field[] fields = clazz.getFields(); for (Field field : fields) { MProperty annotation = field.getAnnotation(MProperty.class); String fieldName = field.getName(); String columnName = null; boolean useSetter = false; if (annotation != null) { columnName = annotation.db_col_name(); useSetter = annotation.useSetter(); } if (columnName == null || columnName.isEmpty()) { columnName = fieldName; } Object value = resultSet.getObject(columnName); if (value != null) { try { if (useSetter) { PropertyUtils.setSimpleProperty(rowObj, fieldName, value); } else { field.setAccessible(true); field.set(rowObj, value); } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); throw new SQLException(String.format("Failed to set value for property '%s'!", fieldName)); } } } return rowObj; }
From source file:com.p5solutions.core.jpa.orm.rowbinder.BasicTypeRowBinder.java
@Override public T mapRow(ResultSet rs, int rowNum) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); // / obviously if we have more than one column, we cannot possibly // map it/*www .j a v a 2 s.co m*/ // / to a plain old java object of type Object.class, since there // are no // / members to map the columns to! if (metaData.getColumnCount() > 1) { throw new RuntimeException("Cannot return multi-column resultset into " + "a plain object of type Object.class. If you need to map a multi-column " + "resultset, please use an object marked with @" + Entity.class + " annotation."); } // // THIS SHOULD NEVER HAPPEN, QUERY EXCEPTION SHOULD // // BE THROWN IF THERE IS A SYNTAX ERROR IN THE QUERY. // if (metaData.getColumnCount() == 0) { } // Otherwise if there is only 1 column, and its within the scope of // plain object.class // returnResults.add((T)rs.getObject(1)); return (T) rs.getObject(1); }
From source file:cosmos.sql.TestSql.java
public void testDistinct() throws SQLException { loadDriverClass();/* ww w . jav a 2s .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 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:com.quangphuong.crawler.dbutil.DBWrapper.java
public List<Object> getEntities(Class<?> entity) { String sql = selectAll.concat(entity.getSimpleName()); Connection con = DBHandler.openConnection(); List<Object> listResult = new ArrayList(); try {/*from w w w . j ava2s . c om*/ Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery(sql); Field[] attributes = entity.getDeclaredFields(); while (resultSet.next()) { List<Object> listFields = new ArrayList(); List<Class<?>> listFieldTypes = new ArrayList(); for (Field attribute : attributes) { attribute.setAccessible(true); if (!attribute.isAnnotationPresent(Ignore.class)) { Object obj = resultSet.getObject(attribute.getName()); listFields.add(obj); listFieldTypes.add(attribute.getType()); } } Object result = entity.getConstructor((Class<?>[]) listFieldTypes.toArray(new Class[0])) .newInstance(listFields.toArray()); listResult.add(result); } } catch (Exception ex) { Logger.getLogger(DBWrapper.class.getName()).log(Level.SEVERE, null, ex); } finally { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return listResult; }
From source file:ResultSetIterator.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) *//*from www . j a va2s. c om*/ public Map toMap(ResultSet rs) throws SQLException { Map result = new CaseInsensitiveHashMap(); ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); for (int i = 1; i <= cols; i++) { result.put(rsmd.getColumnName(i), rs.getObject(i)); } return result; }
From source file:com.bethecoder.ascii_table.impl.JDBCASCIITableAware.java
private void init(ResultSet resultSet) throws SQLException { //Populate header int colCount = resultSet.getMetaData().getColumnCount(); headers = new ArrayList<ASCIITableHeader>(colCount); for (int i = 0; i < colCount; i++) { headers.add(new ASCIITableHeader(resultSet.getMetaData().getColumnLabel(i + 1).toUpperCase())); }// w ww . jav a 2 s . co m //Populate data data = new ArrayList<List<Object>>(); List<Object> rowData = null; List<Object> tempData; while (resultSet.next()) { boolean isAnyColumnMultiline = false; boolean[] columnHasMultiline = new boolean[colCount]; rowData = new ArrayList<Object>(); // figure out if any of the column values need to be split across // multiple lines for (int i = 0; i < colCount; i++) { Object object = resultSet.getObject(i + 1); String val = String.valueOf(object); if (val.contains("\n") || val.length() > maxColumnWidth) { columnHasMultiline[i] = true; isAnyColumnMultiline = true; } rowData.add(object); } if (isAnyColumnMultiline) { // create extra as many extra rows as needed to format // long strings and multiline string int maxRows = 2; Object[][] columns = new Object[colCount][]; for (int i = 0; i < colCount; i++) { if (!columnHasMultiline[i]) continue; String val = String.valueOf(rowData.get(i)); String[] vals = null; if (val.contains("\n")) { vals = val.split("\n"); } else if (val.length() > maxColumnWidth) { String wrap = WordUtils.wrap(val, maxColumnWidth); vals = wrap.split("\n"); } columns[i] = vals; maxRows = Math.max(maxRows, vals.length); } for (int i = 0; i < colCount; i++) { if (columns[i] == null) { columns[i] = padedColumn(rowData.get(i), maxRows); } else if (columns[i].length < maxRows) { Object[] padedArray = new Object[maxRows]; for (int j = 0; j < maxRows; j++) { Object val = j < columns[i].length ? columns[i][j] : ""; padedArray[j] = val; } columns[i] = padedArray; } } for (int r = 0; r < maxRows; r++) { rowData.clear(); for (int c = 0; c < colCount; c++) { rowData.add(columns[c][r]); } data.add(rowData); } } else { data.add(rowData); } } //iterate rows }