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:uk.ac.kcl.rowmappers.DocumentRowMapper.java

private void mapDBFields(Document doc, ResultSet rs) throws SQLException, IOException {
    //add additional query fields for ES export
    ResultSetMetaData meta = rs.getMetaData();

    int colCount = meta.getColumnCount();

    for (int col = 1; col <= colCount; col++) {
        Object value = rs.getObject(col);
        if (value != null) {
            String colLabel = meta.getColumnLabel(col).toLowerCase();
            if (!fieldsToIgnore.contains(colLabel)) {
                DateTime dateTime;/*from w  w  w  .  j av a2  s .c  om*/
                //map correct SQL time types
                switch (meta.getColumnType(col)) {
                case 91:
                    Date dt = (Date) value;
                    dateTime = new DateTime(dt.getTime());
                    doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(),
                            eSCompatibleDateTimeFormatter.print(dateTime));
                    break;
                case 93:
                    Timestamp ts = (Timestamp) value;
                    dateTime = new DateTime(ts.getTime());
                    doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(),
                            eSCompatibleDateTimeFormatter.print(dateTime));
                    break;
                default:
                    doc.getAssociativeArray().put(meta.getColumnLabel(col).toLowerCase(), rs.getString(col));
                    break;
                }
            }
        }

        //map binary content from FS or database if required (as per docman reader)
        if (value != null && meta.getColumnLabel(col).equalsIgnoreCase(binaryContentFieldName)) {
            switch (binaryContentSource) {
            case "database":
                doc.setBinaryContent(rs.getBytes(col));
                break;
            case "fileSystemWithDBPath":
                Resource resource = context.getResource(pathPrefix + rs.getString(col));
                doc.setBinaryContent(IOUtils.toByteArray(resource.getInputStream()));
                break;
            default:
                break;
            }
        }
    }
}

From source file:shell.framework.dao.support.ListExtractor4Map.java

public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnNum = rsmd.getColumnCount();
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    while (rs.next()) {
        Map<String, Object> map4Row = new HashMap<String, Object>();
        for (int i = 1; i <= columnNum; i++) {
            map4Row.put(rsmd.getColumnName(i), rs.getObject(i));
        }/*  w w w  . jav  a 2  s.  c  o m*/
        result.add(map4Row);
    }
    return result;
}

From source file:com.svds.resttest.services.GenericDataService.java

/**
 * Obtain results from query/*from   w w w.ja  v a  2  s.  com*/
 * 
 * @param rs                    result set to process
 * @param genericResultsOutput  output object with metadata about these results
 * @param resultsArrayList      result list to add to
 * @throws SQLException 
 */
private void resultsWithoutMetaData(ResultSet rs, GenericResultsOutput genericResultsOutput,
        List<Object> resultsArrayList) throws SQLException {

    for (int i = 1; i <= genericResultsOutput.getMetaData().size(); i++) {
        resultsArrayList.add(rs.getObject(i));
    }

}

From source file:com.streamsets.pipeline.stage.it.AllPartitionTypesIT.java

@Test
public void testPartitionType() throws Exception {
    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().partitions(partition).build();
    final HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("col", field);
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));

    try {/*from  w  w w  .j a va  2 s. c o m*/
        processRecords(processor, hiveTarget, ImmutableList.of(record));
        if (!supported) {
            Assert.fail("Type is not supported, but yet no exception was thrown");
        }
    } catch (StageException se) {
        if (supported) {
            LOG.error("Processing exception", se);
            Assert.fail("Processing testing record unexpectedly failed: " + se.getMessage());
            throw se;
        } else {
            // We're comparing string here as the class ContainerError is not on classpath
            Assert.assertEquals("CONTAINER_0010", se.getErrorCode().getCode());
            Assert.assertTrue(se.getMessage().contains(Errors.HIVE_METADATA_09.name()));
            // No additional verification necessary
            return;
        }
    }

    assertTableExists("default.tbl");
    assertQueryResult("select * from tbl", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.col", hiveType),
                    new ImmutablePair("tbl.part", hiveType));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(hiveValue, rs.getObject(1));
            Assert.assertEquals(hiveValue, rs.getObject(2));
            Assert.assertFalse("Table tbl contains more then one row", rs.next());
        }
    });
}

From source file:MainClass.java

public MainClass() {
    try {/*from   w w  w.jav a2 s .  c  o m*/
        Class.forName("COM.cloudscape.core.RmiJdbcDriver");
        Connection connection = DriverManager.getConnection("jdbc:cloudscape:rmi:books");
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT * FROM authors");
        ResultSetMetaData metaData = resultSet.getMetaData();
        int numberOfColumns = metaData.getColumnCount();

        for (int i = 1; i <= numberOfColumns; i++) {
            System.out.println(metaData.getColumnName(i) + "\t");
        }

        while (resultSet.next()) {

            for (int i = 1; i <= numberOfColumns; i++) {
                System.out.println(resultSet.getObject(i) + "\t");
            }

            System.out.println("\n");
        }

        statement.close();
        connection.close();
    } catch (SQLException sqlException) {
        System.out.println(sqlException.getMessage());
    } catch (ClassNotFoundException classNotFound) {
        System.out.println("Driver Not Found");
        System.exit(1);
    }
}

From source file:com.baidu.rigel.biplatform.tesseract.dataquery.service.impl.SqlDataQueryServiceImpl.java

/**
 * ?SQL??resultRecord list//from  w w w .java2 s .  c o m
 * @param sqlQuery
 * @param dataSource
 * @param limitStart
 * @param limitEnd
 * @return
 */
private SearchIndexResultSet querySqlList(SqlQuery sqlQuery, DataSource dataSource, long limitStart,
        long limitEnd) {
    long current = System.currentTimeMillis();
    if (sqlQuery == null || dataSource == null || limitEnd < 0) {
        throw new IllegalArgumentException();
    }

    sqlQuery.setLimitMap(limitStart, limitEnd);

    this.initJdbcTemplate(dataSource);

    Meta meta = new Meta(sqlQuery.getSelectList().toArray(new String[0]));
    SearchIndexResultSet resultSet = new SearchIndexResultSet(meta, 1000000);

    jdbcTemplate.query(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement pstmt = con.prepareStatement(sqlQuery.toSql(), ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_READ_ONLY);
            if (con.getMetaData().getDriverName().toLowerCase().contains("mysql")) {
                pstmt.setFetchSize(Integer.MIN_VALUE);
            }
            return pstmt;
        }
    }, new RowCallbackHandler() {

        @Override
        public void processRow(ResultSet rs) throws SQLException {
            List<Object> fieldValues = new ArrayList<Object>();
            String groupBy = "";
            for (String select : sqlQuery.getSelectList()) {
                fieldValues.add(rs.getObject(select));
                if (sqlQuery.getGroupBy() != null && sqlQuery.getGroupBy().contains(select)) {
                    groupBy += rs.getString(select) + ",";
                }
            }

            SearchIndexResultRecord record = new SearchIndexResultRecord(
                    fieldValues.toArray(new Serializable[0]), groupBy);
            resultSet.addRecord(record);
        }
    });
    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "querySqlList",
            "[sqlQuery:" + sqlQuery.toSql() + "][dataSource:" + dataSource + "][limitStart:" + limitStart
                    + "][limitEnd:" + limitEnd + "] cost" + (System.currentTimeMillis() - current + "ms!")));
    return resultSet;
}

From source file:com.github.tosdan.utils.sql.BasicRowProcessorMod.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)
 * @param rs ResultSet that supplies the array data
 * @throws SQLException if a database access error occurs
 * @return the newly created array/* w  w  w. j  av  a 2s . c o m*/
 */
@Override
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.itdaoshi.discuz.dao.CdbUcMembersDAObject.java

@Override
protected Long getNextPrimaryID() {
    QueryRunner run = new QueryRunner();
    ResultSetHandler h = new ResultSetHandler() {
        public Object handle(ResultSet rs) throws SQLException {
            if (!rs.next()) {
                return null;
            }/* w  w w.j a  v  a  2  s. c  o  m*/

            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;
        }
    };
    try {
        Object[] result = (Object[]) run.query(conn, "SELECT MAX(uid) FROM CDB_UC_MEMBERS ", h);
        return (Long) result[0] + 1;
        // do something with the result
    } catch (Exception e) {
        e.printStackTrace();

    }

    return null;
}

From source file:com.arsmentis.cordova.jdbc.Jdbc.java

private JSONArray execute(String sql) throws SQLException, JSONException {
    if (connection == null) {
        throw new SQLException("Not connected");
    }// w  w  w  . j  av  a  2  s  . com

    JSONArray results = new JSONArray();
    Statement statement = connection.createStatement();

    if (statement.execute(sql)) {
        ResultSet resultSet = statement.getResultSet();
        ResultSetMetaData columns = resultSet.getMetaData();

        while (resultSet.next()) {
            JSONObject row = new JSONObject();

            for (int i = 1; i <= columns.getColumnCount(); i++) {
                row.put(columns.getColumnName(i), resultSet.getObject(i));
            }
            results.put(row);
        }

        resultSet.close();
    }

    statement.close();

    return results;
}

From source file:ru.org.linux.user.ProfileDao.java

@Nonnull
public Profile readProfile(@NotNull User user) {
    List<Profile> profiles = jdbcTemplate.query("SELECT settings, main FROM user_settings WHERE id=?",
            new RowMapper<Profile>() {
                @Override// w  w  w .  ja  v  a 2 s  .c o  m
                public Profile mapRow(ResultSet resultSet, int i) throws SQLException {
                    Array boxes = resultSet.getArray("main");

                    if (boxes != null) {
                        return new Profile(
                                new ProfileHashtable(DefaultProfile.getDefaultProfile(),
                                        (Map<String, String>) resultSet.getObject("settings")),
                                Arrays.asList((String[]) boxes.getArray()));
                    } else {
                        return new Profile(new ProfileHashtable(DefaultProfile.getDefaultProfile(),
                                (Map<String, String>) resultSet.getObject("settings")), null);
                    }
                }
            }, user.getId());

    if (profiles.isEmpty()) {
        return new Profile(
                new ProfileHashtable(DefaultProfile.getDefaultProfile(), new HashMap<String, String>()), null);
    } else {
        return profiles.get(0);
    }
}