Example usage for java.sql ResultSet getLong

List of usage examples for java.sql ResultSet getLong

Introduction

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

Prototype

long getLong(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a long in the Java programming language.

Usage

From source file:ar.com.zauber.commons.gis.spots.impl.SQLGeonameSpotDAO.java

/** @see ResultSetExtractor#extractData(java.sql.ResultSet) */
public final Object extractData(final ResultSet rset) throws SQLException, DataAccessException {
    final Collection<GeonameSpot> ret = new ArrayList<GeonameSpot>(rset.getFetchSize());

    while (rset.next()) {
        try {// ww  w . j a  v  a2s. c  om
            final Point point = (Point) reader.read(rset.getString("astext"));
            final GeonameSpot spot = new GeonameSpot(point, rset.getString("name"), rset.getString("ansiname"),
                    rset.getString("countrycode"), rset.getLong("population"));
            spot.setId(rset.getLong("geonameid"));
            ret.add(spot);
        } catch (final ParseException e) {
            throw new RuntimeException(e);
        }
    }
    rset.close();

    return ret;
}

From source file:org.surfnet.cruncher.repository.StatisticsRepositoryImpl.java

@Override
public VersStatistic getVersStats(LocalDate startDate, LocalDate endDate, String spEntityId) {
    final VersStatistic result = new VersStatistic();

    NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(cruncherJdbcTemplate);
    String query = "select idpentityid, sum(entrycount) as loginCount from aggregated_log_logins " + "where "
            + "entryday >= :startDate AND " + "entryday <= :endDate AND " + "spentityid = :spEntityId "
            + "group by idpentityid " + "order by idpentityid";

    Map<String, Object> parameterMap = new HashMap<String, Object>();
    parameterMap.put("startDate", new Date(startDate.toDateMidnight().getMillis()));
    parameterMap.put("endDate", new Date(endDate.toDateMidnight().getMillis()));
    parameterMap.put("spEntityId", spEntityId);

    namedJdbcTemplate.query(query, parameterMap, new RowMapper<VersStatistic>() {

        @Override//from w w  w  .ja v  a 2  s . c  om
        public VersStatistic mapRow(ResultSet rs, int row) throws SQLException {
            String idpEntityId = rs.getString("idpEntityId");
            result.addInstitutionLoginCount(idpEntityId, rs.getLong("loginCount"));

            // no rowbased result
            return null;
        }
    });

    return result;
}

From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value type.
 * <p>Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * @param rs is the ResultSet holding the data
 * @param index is the column index/*  ww w . j  a v a2  s .  com*/
 * @param requiredType the required value type (may be <code>null</code>)
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 */
public static Object getResultSetValue(ResultSet rs, int index, Class requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value = null;
    boolean wasNullCheck = false;

    // Explicitly extract typed value, as far as possible.
    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = Boolean.valueOf(rs.getBoolean(index));
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = Byte.valueOf(rs.getByte(index));
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = Short.valueOf(rs.getShort(index));
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = Integer.valueOf(rs.getInt(index));
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = Long.valueOf(rs.getLong(index));
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = Float.valueOf(rs.getFloat(index));
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = Double.valueOf(rs.getDouble(index));
        wasNullCheck = true;
    } else if (byte[].class.equals(requiredType)) {
        value = rs.getBytes(index);
    } else if (java.sql.Date.class.equals(requiredType)) {
        value = rs.getDate(index);
    } else if (java.sql.Time.class.equals(requiredType)) {
        value = rs.getTime(index);
    } else if (java.sql.Timestamp.class.equals(requiredType) || java.util.Date.class.equals(requiredType)) {
        value = rs.getTimestamp(index);
    } else if (BigDecimal.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (Blob.class.equals(requiredType)) {
        value = rs.getBlob(index);
    } else if (Clob.class.equals(requiredType)) {
        value = rs.getClob(index);
    } else {
        // Some unknown type desired -> rely on getObject.
        value = getResultSetValue(rs, index);
    }

    // Perform was-null check if demanded (for results that the
    // JDBC driver returns as primitives).
    if (wasNullCheck && value != null && rs.wasNull()) {
        value = null;
    }
    return value;
}

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

@Test
public void testRepeatedInsertOverSelectReportsCorrectNumbers() throws Exception {
    Connection conn = methodWatcher.getOrCreateConnection();
    //insert a single record
    conn.createStatement().executeUpdate("insert into T2 (a,b) values (1,1)");
    PreparedStatement ps = conn.prepareStatement("insert into T2 (a,b) select * from T2");
    int iterCount = 10;
    for (int i = 0; i < iterCount; i++) {
        int updateCount = ps.executeUpdate();
        System.out.printf("updateCount=%d%n", updateCount);
        //            Assert.assertEquals("Reported incorrect value!",(1<<i),count);
        ResultSet rs = conn.createStatement().executeQuery("select count(*) from T2");
        Assert.assertTrue("Did not return rows for a count query!", rs.next());
        long count = rs.getLong(1);
        System.out.printf("scanCount=%d%n", count);
        Assert.assertEquals("Incorrect inserted records!", (1 << (i + 1)), count);
    }/*  w ww .java 2  s.c o  m*/

    ResultSet rs = conn.createStatement().executeQuery("select count(*) from T2");
    Assert.assertTrue("Did not return rows for a count query!", rs.next());
    long count = rs.getLong(1);
    Assert.assertEquals("Incorrect inserted records!", (1 << iterCount), count);
}

From source file:com.blackducksoftware.tools.commonframework.standard.codecenter.dao.CodeCenter6_6_1DbDao.java

private long setStatusComment(VulnerabilityPojo vuln, ComponentUsePojo compUse) throws SQLException {
    log.debug("Fetching vulnerability_status_id, comment from componentuser_vulnerability table for vuln ID: "
            + vuln.getId() + " / compUse ID: " + compUse.getId());
    long vulnStatusId = -1;
    Statement stmt = connBdsCatalog.createStatement();
    String sql = "SELECT vulnerability_status_id,comment FROM componentuse_vulnerability "
            + "WHERE vulnerability_id = " + vuln.getId() + " " + "AND componentuse_id = '" + compUse.getId()
            + "'";
    ResultSet rs = stmt.executeQuery(sql);
    if (rs.next()) {
        vulnStatusId = rs.getLong("vulnerability_status_id");
        String vulnStatusComment = rs.getString("comment");
        vuln.setStatusComment(vulnStatusComment);
    }/* w ww .j a  va2 s  .  c om*/
    return vulnStatusId;
}

From source file:com.mirth.connect.server.migration.Migrate3_1_0.java

private void migrateMessageSequences() throws MigrationException {
    try {/*from   www  .  j ava 2s .co m*/
        if (scriptExists(getDatabaseType() + "-3.0.3-3.1.0-create-msg-seq.sql")
                && DatabaseUtil.tableExists(getConnection(), "D_MESSAGE_SEQUENCES")) {
            logger.debug("Migrating message sequences for " + getDatabaseType());

            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;

            try {
                preparedStatement = getConnection()
                        .prepareStatement("SELECT LOCAL_CHANNEL_ID, ID FROM D_MESSAGE_SEQUENCES");
                resultSet = preparedStatement.executeQuery();

                while (resultSet.next()) {
                    Map<String, Object> replacements = new HashMap<String, Object>();
                    replacements.put("localChannelId", resultSet.getLong(1));
                    replacements.put("initialValue", resultSet.getLong(2));

                    logger.debug("Migrating message sequence for local channel ID "
                            + replacements.get("localChannelId") + ", with initial value of "
                            + replacements.get("initialValue"));
                    executeScript(getDatabaseType() + "-3.0.3-3.1.0-create-msg-seq.sql", replacements);
                }
            } finally {
                DbUtils.closeQuietly(resultSet);
                DbUtils.closeQuietly(preparedStatement);
            }

            logger.debug(
                    "Finished creating new message sequence tables, dropping old D_MESSAGE_SEQUENCES table");
            executeStatement("DROP TABLE D_MESSAGE_SEQUENCES");
        }
    } catch (Exception e) {
        throw new MigrationException(
                "An error occurred while migrating message sequences or checking to see if sequences need migration.",
                e);
    }
}

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

@Test
public void correctCases() throws Exception {
    executeUpdate("CREATE TABLE `tbl` (id int, dec decimal(4, 2)) PARTITIONED BY (dt string) STORED AS AVRO");

    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().decimalConfig(4, 2).build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("dec", Field.create(BigDecimal.valueOf(12.12)));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);/*from  w  w w.  j  a v  a 2 s  .  c o m*/

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 2));
    map.put("dec", Field.create(BigDecimal.valueOf(1.0)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 3));
    map.put("dec", Field.create(BigDecimal.valueOf(12.0)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 4));
    map.put("dec", Field.create(BigDecimal.valueOf(0.1)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 5));
    map.put("dec", Field.create(BigDecimal.valueOf(0.12)));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    processRecords(processor, hiveTarget, records);

    assertQueryResult("select * from tbl order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER),
                    new ImmutablePair("tbl.dec", Types.DECIMAL), new ImmutablePair("tbl.dt", Types.VARCHAR));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(1, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(12.12), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(2, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(1), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(3, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(12), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(4, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(0.1), rs.getBigDecimal(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(5, rs.getLong(1));
            Assert.assertEquals(BigDecimal.valueOf(0.12), rs.getBigDecimal(2));

            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
}

From source file:com.blackducksoftware.tools.commonframework.standard.codecenter.dao.CodeCenter6_6_1DbDao.java

private long getNextDatabaseRowId() throws Exception {

    Statement stmt = connBdsCatalog.createStatement();
    String sql = "SELECT nextval( 'hibernate_sequence' )";

    String exceptionMsg = "Empty result set";
    try {//  ww  w  .j  ava2  s.c om
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.next()) {
            long id = rs.getLong(1);
            return id;
        }
    } catch (SQLException e) {
        log.error("Error executing SQL: " + sql);
        exceptionMsg = e.getMessage();
    }
    throw new Exception(
            "Error deriving next datanase record id by reading hibernate_sequence: " + exceptionMsg);
}

From source file:com.px100systems.data.plugin.persistence.jdbc.Storage.java

protected void load(List<String> unitNames, final LoadCallback callback) {
    final LoadData currentRecord = new LoadData();

    StringBuilder where = new StringBuilder();
    if (unitNames != null)
        for (String like : unitNames) {
            if (where.length() > 0)
                where.append(" OR ");
            where.append("(unit_name LIKE '");
            where.append(like);/*from ww  w  . j  a  v  a  2s.  c  o  m*/
            where.append("%')");
        }

    connection.getJdbc().setFetchSize(50);
    connection.getJdbc()
            .query("SELECT unit_name, generator_name, class_name, id, data_size, data FROM " + table
                    + (where.length() > 0 ? (" WHERE " + where) : "")
                    + " ORDER BY unit_name ASC, id ASC, block_number ASC", new RowCallbackHandler() {
                        @Override
                        public void processRow(ResultSet rs) throws SQLException {
                            String unitName = rs.getString("unit_name");
                            String generatorName = rs.getString("generator_name");
                            String className = rs.getString("class_name");
                            Long id = rs.getLong("id");
                            int dataSize = rs.getInt("data_size");
                            byte[] data = rs.getBytes("data");

                            if (currentRecord.id != null && (!currentRecord.id.equals(id)
                                    || !currentRecord.unitName.equals(unitName)))
                                currentRecord.insert(callback);

                            currentRecord.grow(unitName, generatorName, className, id, data, dataSize);
                        }
                    });

    currentRecord.insert(callback);
}

From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java

private void migrateHostDetails(Connection conn) {
    System.out.println("Begin migrate host details");
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {/*  ww  w. jav a  2  s  . c o m*/
        pstmt = conn.prepareStatement("select id, value from host_details where name = 'password'");
        rs = pstmt.executeQuery();
        while (rs.next()) {
            long id = rs.getLong(1);
            String value = rs.getString(2);
            if (value == null || value.isEmpty()) {
                continue;
            }
            String encryptedValue = migrateValue(value);
            pstmt = conn.prepareStatement("update host_details set value=? where id=?");
            pstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
            pstmt.setLong(2, id);
            pstmt.executeUpdate();
        }
    } catch (SQLException e) {
        throw new CloudRuntimeException("Unable update host_details values ", e);
    } catch (UnsupportedEncodingException e) {
        throw new CloudRuntimeException("Unable update host_details values ", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }

            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
        }
    }
    System.out.println("End migrate host details");
}