Example usage for java.sql ResultSet getObject

List of usage examples for java.sql ResultSet getObject

Introduction

In this page you can find the example usage for java.sql ResultSet getObject.

Prototype

Object getObject(String columnLabel) throws SQLException;

Source Link

Document

Gets the value of the designated column in the current row of this ResultSet object as an Object in the Java programming language.

Usage

From source file:com.netspective.axiom.sql.ResultSetUtils.java

public Object[] getResultSetSingleRowArray(ResultSet rs) throws SQLException {
    if (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colsCount = rsmd.getColumnCount();
        Object[] result = new Object[colsCount];
        for (int i = 1; i <= colsCount; i++) {
            result[i - 1] = rs.getObject(i);
        }/*from  w  w  w .  ja  v  a 2 s  . c  o  m*/
        return result;
    } else
        return null;
}

From source file:com.netspective.axiom.sql.ResultSetUtils.java

public Object[] getResultSetSingleRowAsArray(ResultSet rs) throws SQLException {
    if (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colsCount = rsmd.getColumnCount();
        Object[] result = new Object[colsCount];
        for (int i = 1; i <= colsCount; i++) {
            result[i - 1] = rs.getObject(i);
        }/*from  w w  w.  j a v  a 2s. c om*/
        return result;
    } else
        return null;
}

From source file:io.stallion.dataAccess.BeanListHandler.java

public List<T> handle(ResultSet rs) throws SQLException {
    List<T> beans = list();
    String[] columnToProperty = null;
    while (rs.next()) {
        try {/*from   ww  w.  j  av a 2s .  c o  m*/
            if (columnToProperty == null) {
                columnToProperty = makeColumnToProperty(rs.getMetaData(), PropertyUtils.getPropertyNames(type));
            }
            T bean = (T) type.newInstance();
            for (int i = 1; i < columnToProperty.length; i++) {
                Object val = rs.getObject(i);
                String propertyName = columnToProperty[i];
                if (empty(propertyName)) {
                    continue;
                }
                PropertyUtils.setProperty(bean, propertyName, val);
            }
            beans.add(bean);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
    return beans;
}

From source file:com.manydesigns.portofino.persistence.QueryUtils.java

/**
 * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by
 * {@link PreparedStatement}./*w w w.j  a v a  2 s. co m*/
 * 
 * @param session the session
 * @param queryString the query
 * @param parameters parameters to substitute in the query
 * @return the results of the query as an Object[] (an array cell per column)
 */
// hongliangpan add
public static List<Map<String, Object>> runSqlReturnMap(Session session, final String queryString,
        final Object[] parameters) {
    final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    try {
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(queryString);
                ResultSet rs = null;
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        stmt.setObject(i + 1, parameters[i]);
                    }
                    rs = stmt.executeQuery();
                    ResultSetMetaData md = rs.getMetaData();
                    int cc = md.getColumnCount();

                    while (rs.next()) {
                        Map<String, Object> t_row = new LinkedHashMap<String, Object>();
                        for (int i = 0; i < cc; i++) {
                            Object t_value = rs.getObject(i + 1);
                            t_row.put(md.getColumnLabel(i + 1), t_value);
                        }
                        result.add(t_row);
                    }
                } finally {
                    if (null != rs) {
                        rs.close();
                    }
                    if (null != stmt) {
                        stmt.close();
                    }
                }
            }
        });
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        session.beginTransaction();
        throw e;
    }

    return result;
}

From source file:com.icsshs.datatransfer.database.impl.QueryBeanProcessor.java

/**
 * Convert a <code>ResultSet</code> column into an object.  Simple
 * implementations could just call <code>rs.getObject(index)</code> while
 * more complex implementations could perform type manipulation to match
 * the column's type to the bean property type.
 *
 * <p>//from   w w  w.  j  a  v  a  2  s .c  o m
 * This implementation calls the appropriate <code>ResultSet</code> getter
 * method for the given property type to perform the type conversion.  If
 * the property type doesn't match one of the supported
 * <code>ResultSet</code> types, <code>getObject</code> is called.
 * </p>
 *
 * @param rs The <code>ResultSet</code> currently being processed.  It is
 * positioned on a valid row before being passed into this method.
 *
 * @param index The current column index being processed.
 *
 * @param propType The bean property type that this column needs to be
 * converted into.
 *
 * @throws SQLException if a database access error occurs
 *
 * @return The object from the <code>ResultSet</code> at the given column
 * index after optional type processing or <code>null</code> if the column
 * value was SQL NULL.
 */
protected Object processColumn(ResultSet rs, int index, Class<?> propType) throws SQLException {

    if (!propType.isPrimitive() && rs.getObject(index) == null) {
        return null;
    }

    if (propType.equals(String.class)) {
        return rs.getString(index);

    } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
        return Integer.valueOf(rs.getInt(index));

    } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) {
        return Boolean.valueOf(rs.getBoolean(index));

    } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) {
        return Long.valueOf(rs.getLong(index));

    } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) {
        return Double.valueOf(rs.getDouble(index));

    } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) {
        return Float.valueOf(rs.getFloat(index));

    } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) {
        return Short.valueOf(rs.getShort(index));

    } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) {
        return Byte.valueOf(rs.getByte(index));

    } else if (propType.equals(Timestamp.class)) {
        return rs.getTimestamp(index);

    } else if (propType.equals(byte[].class)) {
        return rs.getBytes(index);

    } else {
        return rs.getObject(index);

    }

}

From source file:net.solarnetwork.node.dao.jdbc.consumption.JdbcConsumptionDatumDao.java

@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public List<ConsumptionDatum> getDatumNotUploaded(String destination) {
    return findDatumNotUploaded(new RowMapper<ConsumptionDatum>() {

        @Override/*from www. j  av  a2  s  .  c om*/
        public ConsumptionDatum mapRow(ResultSet rs, int rowNum) throws SQLException {
            if (log.isTraceEnabled()) {
                log.trace("Handling result row " + rowNum);
            }
            ConsumptionDatum datum = new ConsumptionDatum();
            int col = 1;
            datum.setCreated(rs.getTimestamp(col++));
            datum.setSourceId(rs.getString(col++));

            Number val = (Number) rs.getObject(col++);
            datum.setLocationId(val == null ? null : val.longValue());

            val = (Number) rs.getObject(col++);
            datum.setWatts(val == null ? null : val.intValue());

            val = (Number) rs.getObject(col++);
            datum.setWattHourReading(val == null ? null : val.longValue());

            return datum;
        }
    });
}

From source file:info.naiv.lab.java.tool.sqlite.exporter.component.ValueHandlerImpl.java

/**
 *
 * @param field/*from  ww w. j  ava 2  s.  c  o m*/
 * @param rowSet
 * @return
 * @throws SQLException
 */
@Override
public Object handleValue(Field field, ResultSet rowSet) throws SQLException {
    String name = field.getOriginalName();
    switch (field.getTypeInfo()) {
    case CHAR:
    case NCHAR:
        return StringUtils.trimTrailingWhitespace(rowSet.getString(name));
    case DATE:
        return Objects.toString(rowSet.getDate(name), null);
    case TIME:
        return Objects.toString(rowSet.getTime(name), null);
    case TIMESTAMP:
        return Objects.toString(rowSet.getTimestamp(name), null);
    default:
        return rowSet.getObject(name);
    }
}

From source file:com.manydesigns.portofino.model.database.ConnectionProvider.java

protected void readType(ResultSet typeRs) throws SQLException {
    String typeName = typeRs.getString("TYPE_NAME");
    int dataType = typeRs.getInt("DATA_TYPE");
    Integer maximumPrecision;/*from  w  w w  .  j a  va2 s .c o  m*/
    Object maximumPrecisionObj = typeRs.getObject("PRECISION");
    if (maximumPrecisionObj instanceof Number) {
        maximumPrecision = ((Number) maximumPrecisionObj).intValue();
    } else {
        maximumPrecision = null;
        logger.warn("Cannot get maximum precision for type: {} value: {}", typeName, maximumPrecisionObj);
    }
    String literalPrefix = typeRs.getString("LITERAL_PREFIX");
    String literalSuffix = typeRs.getString("LITERAL_SUFFIX");
    boolean nullable = (typeRs.getShort("NULLABLE") == DatabaseMetaData.typeNullable);
    boolean caseSensitive = typeRs.getBoolean("CASE_SENSITIVE");
    boolean searchable = (typeRs.getShort("SEARCHABLE") == DatabaseMetaData.typeSearchable);
    boolean autoincrement = typeRs.getBoolean("AUTO_INCREMENT");
    short minimumScale = typeRs.getShort("MINIMUM_SCALE");
    short maximumScale = typeRs.getShort("MAXIMUM_SCALE");

    Type type = new Type(typeName, dataType, maximumPrecision, literalPrefix, literalSuffix, nullable,
            caseSensitive, searchable, autoincrement, minimumScale, maximumScale);
    types.add(type);
}

From source file:net.hydromatic.optiq.test.JdbcTest.java

static String toString(ResultSet resultSet) throws SQLException {
    StringBuilder buf = new StringBuilder();
    while (resultSet.next()) {
        int n = resultSet.getMetaData().getColumnCount();
        String sep = "";
        for (int i = 1; i <= n; i++) {
            buf.append(sep).append(resultSet.getMetaData().getColumnLabel(i)).append("=")
                    .append(resultSet.getObject(i));
            sep = "; ";
        }/*from   w w  w.  j  av  a  2s  .  co  m*/
        buf.append("\n");
    }
    return buf.toString();
}

From source file:org.apache.drill.test.framework.Utils.java

public static String getSqlResult(ResultSet resultSet) throws SQLException {
    StringBuffer stringBuffer = new StringBuffer();
    List columnLabels = new ArrayList<String>();

    try {/*  w w w  .  j  a  va 2s .co m*/
        int columnCount = resultSet.getMetaData().getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            columnLabels.add(resultSet.getMetaData().getColumnLabel(i));
        }
        List<Integer> types = Lists.newArrayList();
        for (int i = 1; i <= columnCount; i++) {
            types.add(resultSet.getMetaData().getColumnType(i));
        }

        LOG.debug("Result set data types:");
        LOG.debug(Utils.getTypesInStrings(types));
        stringBuffer.append(new ColumnList(types, columnLabels).toString() + "\n");

        while (resultSet.next()) {
            List<Object> values = Lists.newArrayList();
            for (int i = 1; i <= columnCount; i++) {
                try {
                    if (resultSet.getObject(i) == null) {
                        values.add(null);
                        continue;
                    }
                    if (resultSet.getMetaData().getColumnType(i) == Types.NVARCHAR) {
                        values.add(new String(resultSet.getBytes(i), "UTF-16"));
                    } else {
                        values.add(new String(resultSet.getBytes(i), "UTF-8"));
                    }
                } catch (Exception e) {
                    if (resultSet.getMetaData().getColumnType(i) == Types.DATE) {
                        values.add(resultSet.getDate(i));
                    } else {
                        values.add(resultSet.getObject(i));
                    }
                }
            }
            stringBuffer.append(new ColumnList(types, values).toString() + "\n");
        }
    } catch (IllegalArgumentException | IllegalAccessException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
    return stringBuffer.toString();
}