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.healthmarketscience.jackcess.util.ImportUtil.java

/**
 * Copy an existing JDBC ResultSet into a new (or optionally existing) table
 * in this database.// w  w w.  j a  v  a  2s .c o m
 * 
 * @param name Name of the new table to create
 * @param source ResultSet to copy from
 * @param filter valid import filter
 * @param useExistingTable if {@code true} use current table if it already
 *                         exists, otherwise, create new table with unique
 *                         name
 *
 * @return the name of the imported table
 * 
 * @see Builder
 */
public static String importResultSet(ResultSet source, Database db, String name, ImportFilter filter,
        boolean useExistingTable) throws SQLException, IOException {
    ResultSetMetaData md = source.getMetaData();

    name = TableBuilder.escapeIdentifier(name);
    Table table = null;
    if (!useExistingTable || ((table = db.getTable(name)) == null)) {
        List<ColumnBuilder> columns = toColumns(md);
        table = createUniqueTable(db, name, columns, md, filter);
    }

    List<Object[]> rows = new ArrayList<Object[]>(COPY_TABLE_BATCH_SIZE);
    int numColumns = md.getColumnCount();

    while (source.next()) {
        Object[] row = new Object[numColumns];
        for (int i = 0; i < row.length; i++) {
            row[i] = source.getObject(i + 1);
        }
        row = filter.filterRow(row);
        if (row == null) {
            continue;
        }
        rows.add(row);
        if (rows.size() == COPY_TABLE_BATCH_SIZE) {
            table.addRows(rows);
            rows.clear();
        }
    }
    if (rows.size() > 0) {
        table.addRows(rows);
    }

    return table.getName();
}

From source file:dbconverter.dao.util.ToolKit.java

/**
 * Given a ResultSet, writes the contained data as JSON to a target file,
 *  with the expectation that said file will be used in an Elasticsearch
 *  bulk index operation.//  w  w  w  .j av a  2 s .c o m
 * This method supports arbitrary-sized ResultSets, provided interval is set low enough
 * @param resultSet The ResultSet to save to a file
 * @param obj A QueryObject which must contain the index and type of the target
 * @param interval Determines how many documents should be stored within Java at a time
 *                 If you run out of heap space, try decreasing this value
 * @param fileName The name of the file to write to
 * @author hightowe
 */
public static void writeResultSetToJson(ResultSet resultSet, QueryObject obj, int interval, String fileName) {
    assert resultSet != null : "ResultSet cannont be null!";

    List<String> resultsList = new ArrayList<>();

    try {
        ResultSetMetaData rsMetaData = resultSet.getMetaData();
        int columnNumbers = rsMetaData.getColumnCount();
        int count = 0;
        int prev = 0;
        while (resultSet.next()) {
            Map<String, Object> dataMap = new HashMap<>();

            // add all column names to the map key-set
            for (int i = 1; i <= columnNumbers; i++) {
                dataMap.put(rsMetaData.getColumnLabel(i), resultSet.getObject(i));
            }

            dataMap.put(TIME_STAMP, getISOTime(TIME_STAMP_FORMAT));

            // Add the data to List of Maps
            String json = ToolKit.convertMapToJson(dataMap);
            resultsList.add(json);
            count++;

            // write to file after every (interval)th run, then clear
            // resultsList to avoid heap space errors
            if (count % interval == 0) {
                writeJsonStringsToFile(resultsList, fileName, obj, prev);
                prev += interval;
                resultsList.clear();
            }
        }

        writeJsonStringsToFile(resultsList, fileName, obj, prev);

    } catch (SQLException e) {
        logger.error(e);
    }
}

From source file:com.microsoft.tfs.core.internal.db.DBStatement.java

/**
 * Convenience query that returns an array of a primitive component type.
 *///from   w  w  w .  j a v a  2 s.c  om
public Object executeQueryForPrimitiveArray(final Object params, final Class primitiveType) {
    if (primitiveType == null || !primitiveType.isPrimitive()) {
        throw new IllegalArgumentException("primitiveType must be a non-null primitive type"); //$NON-NLS-1$
    }

    final List results = new ArrayList();

    executeQuery(params, new ResultHandler() {
        @Override
        public void handleRow(final ResultSet rset) throws SQLException {
            results.add(rset.getObject(1));
        }
    });

    final int len = results.size();
    final Object returnArray = Array.newInstance(primitiveType, len);

    for (int i = 0; i < len; i++) {
        Array.set(returnArray, i, results.get(i));
    }

    return returnArray;
}

From source file:net.sf.jdbcwrappers.trim.TrimmingTest.java

@Test
public void testStatement() throws SQLException {
    Statement statement = connection.createStatement();
    try {//from   w w  w.j a  va 2s .c om
        ResultSet rs = statement
                .executeQuery("SELECT INT_COL, CHAR_COL, VARCHAR_COL, CHAR_COL2 AS MYCHARLABEL FROM TEST");
        rs.next();
        assertEquals("test", rs.getString(2));
        assertEquals("test", rs.getString("CHAR_COL"));
        assertEquals("test", rs.getObject(2));
        assertEquals("test", rs.getObject("CHAR_COL"));
        assertEquals("test2", rs.getString(4));
        assertEquals("test2", rs.getString("MYCHARLABEL"));
        assertEquals("test2", rs.getObject(4));
        assertEquals("test2", rs.getObject("MYCHARLABEL"));
    } finally {
        statement.close();
    }
}

From source file:Main.java

public Main() throws Exception {
    ArrayList columnNames = new ArrayList();
    ArrayList data = new ArrayList();
    String url = "jdbc:mysql://localhost:3306/yourdb";
    String userid = "root";
    String password = "sesame";
    String sql = "SELECT * FROM animals";

    Connection connection = DriverManager.getConnection(url, userid, password);
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    for (int i = 1; i <= columns; i++) {
        columnNames.add(md.getColumnName(i));
    }//from   w  w w  .ja v  a 2 s  . co m
    while (rs.next()) {
        ArrayList row = new ArrayList(columns);
        for (int i = 1; i <= columns; i++) {
            row.add(rs.getObject(i));
        }
        data.add(row);
    }
    Vector columnNamesVector = new Vector();
    Vector dataVector = new Vector();
    for (int i = 0; i < data.size(); i++) {
        ArrayList subArray = (ArrayList) data.get(i);
        Vector subVector = new Vector();
        for (int j = 0; j < subArray.size(); j++) {
            subVector.add(subArray.get(j));
        }
        dataVector.add(subVector);
    }
    for (int i = 0; i < columnNames.size(); i++)
        columnNamesVector.add(columnNames.get(i));
    JTable table = new JTable(dataVector, columnNamesVector) {
        public Class getColumnClass(int column) {
            for (int row = 0; row < getRowCount(); row++) {
                Object o = getValueAt(row, column);
                if (o != null) {
                    return o.getClass();
                }
            }
            return Object.class;
        }
    };
    JScrollPane scrollPane = new JScrollPane(table);
    getContentPane().add(scrollPane);
    JPanel buttonPanel = new JPanel();
    getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}

From source file:net.bitnine.agensgraph.test.ReturnTest.java

public void testSimpleBind() throws Exception {
    ResultSet rs;
    PreparedStatement pstmt = con.prepareStatement("RETURN ?");

    Jsonb data = new Jsonb();
    data.setJsonValue(JsonObject.create("{\"name\":\"ktlee\"}"));
    pstmt.setObject(1, data);/*from w  ww  .  j a v  a  2 s  .  c o m*/
    rs = pstmt.executeQuery();
    while (rs.next()) {
        JsonObject jo = ((Jsonb) rs.getObject(1)).getJsonObject();
        assertEquals("ktlee", jo.getString("name"));
    }
    rs.close();

    Map<String, Object> jobj = new HashMap<>();
    jobj.put("name", "ktlee");
    jobj.put("age", 41);
    data.setJsonValue(JsonObject.create(jobj));
    pstmt.setObject(1, data);
    rs = pstmt.executeQuery();
    while (rs.next()) {
        JsonObject jo = ((Jsonb) rs.getObject(1)).getJsonObject();
        assertEquals(41, jo.getInt("age").intValue());
    }
    rs.close();

    JsonObject jo = JsonObject.create(jobj);
    jo.put("id", JsonArray.create(1, 2, 3));
    pstmt.setObject(1, jo);
    rs = pstmt.executeQuery();
    while (rs.next()) {
        jo = ((Jsonb) rs.getObject(1)).getJsonObject();
        assertEquals(3, (int) jo.getArray("id").getInt(2));
    }
    rs.close();

    data.setJsonValue(10);
    pstmt.setObject(1, data);
    rs = pstmt.executeQuery();
    while (rs.next()) {
        assertEquals(10, (int) ((Jsonb) rs.getObject(1)).getInt());
    }
    rs.close();
    pstmt.close();
}

From source file:com.chiorichan.database.SqlTable.java

protected Object toObject(Object clz, ResultSet rs) throws SQLException {
    Validate.notNull(clz);//from w  w  w .j a v  a2  s .  c  o  m
    Validate.notNull(rs);

    if (rs.getRow() == 0)
        rs.first();

    for (Field f : clz.getClass().getDeclaredFields()) {
        SqlColumn sc = f.getAnnotation(SqlColumn.class);

        try {
            if (sc != null && rs.getObject(sc.name()) != null) {
                Object obj = rs.getObject(sc.name());
                if (f.getType().equals(String.class)) {
                    f.set(clz, ObjectUtil.castToString(obj));
                } else if (obj instanceof String && (f.getType().equals(Long.class)
                        || f.getType().getSimpleName().equalsIgnoreCase("long"))) {
                    f.set(clz, Long.parseLong((String) obj));
                } else if (obj instanceof String && (f.getType().equals(Integer.class)
                        || f.getType().getSimpleName().equalsIgnoreCase("int"))) {
                    f.set(clz, Integer.parseInt((String) obj));
                } else {
                    f.set(clz, obj);
                }
            }
        } catch (IllegalArgumentException e) {
            Loader.getLogger()
                    .severe("We can't cast the value '" + rs.getObject(sc.name()) + "' from column `"
                            + sc.name() + "` with type `" + rs.getObject(sc.name()).getClass().getSimpleName()
                            + "` to FIELD `" + f.getName() + "` with type `" + f.getType() + "`.");
        } catch (IllegalAccessException e) {
            Loader.getLogger().severe("We don't have access to FIELD `" + f.getName()
                    + "`, Be sure the field has a PUBLIC modifier.");
        }
    }

    return clz;
}

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

@Test
public void testType() throws Exception {
    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().build();
    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 {/*  w  w w  .  j  a v  a  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 {
            Assert.assertEquals(Errors.HIVE_19, se.getErrorCode());
            // 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.dt", Types.VARCHAR));

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

From source file:com.splicemachine.derby.impl.sql.execute.operations.joins.JoinIT.java

@Test
public void testSubqueryAndHashableJoin() throws Exception {

    String sqlText = "select t3.c1 ||  '; ' \n" + "from    t1 \n"
            + "        left outer join (Select c1 FROM t2)   a13\n" + "          on    (t1.c4 = a13.c1)\n"
            + "        left outer join joinit.t3\n" + "          on    (t1.c5 = t3.c1)\n"
            + "        left outer join joinit.t4\n" + "          on    (t1.c6 = CAST(t4.c1 as CHAR(6)))\n"
            + "        left outer join joinit.t5\n" + "          on    (SUBSTR(t1.c7,1, 3) = t5.c1)";

    ResultSet rs = methodWatcher.prepareStatement(sqlText).executeQuery();
    Assert.assertTrue(rs.next());//www . jav  a  2  s . co  m
    Assert.assertNull(rs.getObject(1));

    sqlText = "select  \n" + "SUBSTR(CHAR(t7.c1),1,3)\n" + "from  t6\n"
            + "left outer join (select SUBSTR(CHAR(c1),1,3) as c2 from t7) a119\n" + "on  (t6.c2 = a119.c2)\n"
            + "left outer join t7\n" + "on  (t6.c3 = SUBSTR(CHAR(t7.c1),1,3) )\n" + "left outer join t8\n"
            + "on  (SUBSTR(t6.c4,1,3) = t8.c1)\n" + "where t6.c1 = '123456789'";
    rs = methodWatcher.prepareStatement(sqlText).executeQuery();
    Assert.assertTrue(rs.next());
    Assert.assertNull(rs.getObject(1));
}

From source file:eu.trentorise.smartcampus.permissionprovider.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 . j a  va  2s.c o  m
    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>());
    }
    return details;
}