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:com.phantom.hadoop.examples.DBCountPageView.java

/** Verifies the results are correct */
private boolean verify() throws SQLException {
    // check total num pageview
    String countAccessQuery = "SELECT COUNT(*) FROM Access";
    String sumPageviewQuery = "SELECT SUM(pageview) FROM Pageview";
    Statement st = null;//ww  w  . java2  s .c  o m
    ResultSet rs = null;
    try {
        st = connection.createStatement();
        rs = st.executeQuery(countAccessQuery);
        rs.next();
        long totalPageview = rs.getLong(1);

        rs = st.executeQuery(sumPageviewQuery);
        rs.next();
        long sumPageview = rs.getLong(1);

        LOG.info("totalPageview=" + totalPageview);
        LOG.info("sumPageview=" + sumPageview);

        return totalPageview == sumPageview && totalPageview != 0;
    } finally {
        if (st != null)
            st.close();
        if (rs != null)
            rs.close();
    }
}

From source file:de.ingrid.importer.udk.strategy.v1.IDCStrategy1_0_5.java

private void updateT03Catalogue() throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Updating t03_catalogue...");
    }/*  w  w  w  .ja v  a 2  s. co m*/

    if (log.isInfoEnabled()) {
        log.info("Map old country_code, language_code to new country_key/_value, language_key/_value ...");
    }

    // then add entries for ALL t01_objects (no matter whether working or published version) 
    String sql = "select distinct id, cat_name, country_code, language_code from t03_catalogue";

    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery(sql, st);
    while (rs.next()) {
        long catId = rs.getLong("id");
        String catName = rs.getString("cat_name");
        String catalogCountryShortcut = rs.getString("country_code");
        catalogLanguageShortcut = rs.getString("language_code");

        // determine country, default is "germany". Can be edited via IGE.
        Integer newCountryCode = UtilsCountryCodelist.getCodeFromShortcut(catalogCountryShortcut);
        if (newCountryCode == null) {
            log.error("!!! Problems determining country of catalog from t03_catalogue.country_code '"
                    + catalogCountryShortcut + "' ! We set country to GERMANY !");
            newCountryCode = UtilsCountryCodelist.NEW_COUNTRY_KEY_GERMANY;
        }
        String newCountryName = UtilsCountryCodelist.getNameFromCode(newCountryCode, catalogLanguageShortcut);

        // determine language
        Integer newLangCode = UtilsLanguageCodelist.getCodeFromShortcut(catalogLanguageShortcut);
        String newLangName = UtilsLanguageCodelist.getNameFromCode(newLangCode, catalogLanguageShortcut);

        // update
        jdbc.executeUpdate("UPDATE t03_catalogue SET " + "country_key = " + newCountryCode
                + ", country_value = '" + newCountryName + "'" + ", language_key = " + newLangCode
                + ", language_value = '" + newLangName + "' " + " WHERE id = " + catId);

        if (log.isInfoEnabled()) {
            log.info("Updated catalog " + catName + " to " + "country: '" + newCountryCode + "'/'"
                    + newCountryName + "'" + ", language:" + newLangCode + "'/'" + newLangName + "'");
        }
    }
    rs.close();
    st.close();

    if (log.isInfoEnabled()) {
        log.info("Updating t03_catalogue... done");
    }
}

From source file:org.waarp.common.database.data.AbstractDbData.java

/**
 * Get one value into DbValue from ResultSet
 * /*from  w  w w .j av a 2s .  c  om*/
 * @param rs
 * @param value
 * @throws WaarpDatabaseSqlException
 */
static public void getTrueValue(ResultSet rs, DbValue value) throws WaarpDatabaseSqlException {
    try {
        switch (value.type) {
        case Types.VARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.LONGVARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.BIT:
            value.value = rs.getBoolean(value.column);
            break;
        case Types.TINYINT:
            value.value = rs.getByte(value.column);
            break;
        case Types.SMALLINT:
            value.value = rs.getShort(value.column);
            break;
        case Types.INTEGER:
            value.value = rs.getInt(value.column);
            break;
        case Types.BIGINT:
            value.value = rs.getLong(value.column);
            break;
        case Types.REAL:
            value.value = rs.getFloat(value.column);
            break;
        case Types.DOUBLE:
            value.value = rs.getDouble(value.column);
            break;
        case Types.VARBINARY:
            value.value = rs.getBytes(value.column);
            break;
        case Types.DATE:
            value.value = rs.getDate(value.column);
            break;
        case Types.TIMESTAMP:
            value.value = rs.getTimestamp(value.column);
            break;
        case Types.CLOB:
            value.value = rs.getClob(value.column).getCharacterStream();
            break;
        case Types.BLOB:
            value.value = rs.getBlob(value.column).getBinaryStream();
            break;
        default:
            throw new WaarpDatabaseSqlException("Type not supported: " + value.type + " for " + value.column);
        }
    } catch (SQLException e) {
        DbSession.error(e);
        throw new WaarpDatabaseSqlException("Getting values in error: " + value.type + " for " + value.column,
                e);
    }
}

From source file:org.geowebcache.storage.MetastoreRemover.java

private void migrateTileDates(JdbcTemplate template, final FilePathGenerator generator) {
    String query = "select layers.value as layer, gridsets.value as gridset, "
            + "tiles.parameters_id, tiles.z, tiles.x, tiles.y, created, formats.value as format \n"
            + "from tiles join layers on layers.id = tiles.layer_id \n"
            + "join gridsets on gridsets.id = tiles.gridset_id \n"
            + "join formats on formats.id = tiles.format_id \n"
            + "order by layer_id, parameters_id, gridset, z, x, y";

    final long total = template.queryForLong("select count(*) from (" + query + ")");
    log.info("Migrating " + total + " tile creation dates from the metastore to the file system");

    template.query(query, new RowCallbackHandler() {

        int count = 0;

        public void processRow(ResultSet rs) throws SQLException {
            // read the result set
            String layer = rs.getString(1);
            String gridset = rs.getString(2);
            String paramsId = rs.getString(3);
            long z = rs.getLong(4);
            long x = rs.getLong(5);
            long y = rs.getLong(6);
            long created = rs.getLong(7);
            String format = rs.getString(8);

            // create the tile and thus the tile path
            TileObject tile = TileObject.createCompleteTileObject(layer, new long[] { x, y, z }, gridset,
                    format, null, null);
            tile.setParametersId(paramsId);
            try {
                File file = generator.tilePath(tile, MimeType.createFromFormat(format));

                // update the last modified according to the date
                if (file.exists()) {
                    file.setLastModified(created);
                }/*from  w ww . j a  v  a 2  s. com*/
            } catch (MimeException e) {
                log.error("Failed to locate mime type for format '" + format + "', this should never happen!");
            }

            count++;
            if (count % 10000 == 0 || count >= total) {
                log.info("Migrated " + count + "/" + total
                        + " tile creation dates from the metastore to the file system");
            }
        }
    });
}

From source file:esg.node.components.metrics.MetricsUsersDAO.java

protected void buildResultSetHandler() {
    log.trace("Setting up result handler");
    metricsUsersHandler = new ResultSetHandler<List<MetricsUsersDAO.UserInfo>>() {
        public List<MetricsUsersDAO.UserInfo> handle(ResultSet rs) throws SQLException {
            List<MetricsUsersDAO.UserInfo> userInfos = new Vector<UserInfo>();
            UserInfo userInfo = new UserInfo();
            if (!rs.next())
                return userInfos;
            do {//from w w w. j  ava 2  s  . c om
                userInfo.userid = rs.getString(1);
                userInfo.count = rs.getInt(2);
                userInfo.sum = rs.getLong(3);
                userInfo = new UserInfo();
            } while (rs.next());
            return userInfos;
        }
    };
}

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

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

    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().decimalConfig(2, 0).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)));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);//from  w  ww  .j a v  a 2  s .  c om

    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), rs.getBigDecimal(2));

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

From source file:com.mobilewallet.common.dao.LoginDAO.java

public User login(String email, String password) {
    User user = null;//from ww  w.j  a va  2s  . com
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        connection = dataSource.getConnection();
        pstmt = connection.prepareStatement(loginEmailAndPwdQuery);
        pstmt.setString(1, email);
        pstmt.setString(2, password);

        rs = pstmt.executeQuery();

        if (rs.next()) {
            user = new User();
            user.setUserId(rs.getLong("u_id"));
            user.setEmail(rs.getString("u_email"));
            user.setName(rs.getString("u_name"));
            user.setMyRefCode(rs.getString("u_my_ref_code"));
            user.setFriendRefCode(rs.getString("u_friend_ref_code"));
            user.setAmount(rs.getFloat("w_amount"));
            log.info("Amount In DAO : " + rs.getFloat("w_amount"));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception ex) {

        }
    }
    return user;
}

From source file:com.splicemachine.mrio.api.core.SMSQLUtil.java

public long getChildTransactionID(Connection conn, long parentTxsID, String tableName) throws SQLException {
    PreparedStatement ps = null;//from  w w  w.ja v  a 2  s .co  m
    ResultSet rs = null;
    long childTxsID;
    try {
        ps = conn.prepareStatement("call SYSCS_UTIL.SYSCS_START_CHILD_TRANSACTION(?,?)");
        ps.setLong(1, parentTxsID);
        ps.setString(2, tableName);
        ResultSet rs3 = ps.executeQuery();
        rs3.next();
        childTxsID = rs3.getLong(1);
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
    }
    return childTxsID;
}

From source file:de.lsvn.dao.UserDao.java

public int validateToken(String token) {
    connection = DbUtil.getConnection();
    try {/*from  ww w.  j a va2s  .c om*/

        Date date = new Date();
        long timestamp = date.getTime();

        PreparedStatement cleanupStatement = connection
                .prepareStatement("DELETE FROM password_change_requests WHERE Time < ?; ");
        cleanupStatement.setString(1, String.valueOf(timestamp - 3600000L));
        cleanupStatement.executeUpdate();
        DbUtil.closePreparedStatement(cleanupStatement);

        PreparedStatement preparedStatement = connection
                .prepareStatement("SELECT Token, Time, UserID FROM password_change_requests");
        ResultSet rs = preparedStatement.executeQuery();

        while (rs.next()) {
            try {
                String storedToken = rs.getString("Token");
                long storedTimestamp = rs.getLong("Time");
                int usr = rs.getInt("UserID");
                if (PasswordHash.validatePassword(token, storedToken)
                        && timestamp < storedTimestamp + 3600000) {
                    return usr;
                }
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvalidKeySpecException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        DbUtil.closeResultSet(rs);
        DbUtil.closePreparedStatement(preparedStatement);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtil.closeConnection(connection);
    }

    return -1;
}

From source file:eionet.cr.dao.virtuoso.VirtuosoSpoBinaryDAO.java

public SpoBinaryDTO get(String subjectUri) throws DAOException {

    if (StringUtils.isBlank(subjectUri)) {
        throw new IllegalArgumentException("Subject uri must not be blank");
    }//from w  w w .j a  va  2  s.  c  o  m

    ResultSet rs = null;
    PreparedStatement stmt = null;
    Connection conn = null;
    try {
        conn = getSQLConnection();
        stmt = conn.prepareStatement(SQL_GET);
        stmt.setLong(1, Hashes.spoHash(subjectUri));
        rs = stmt.executeQuery();
        if (rs != null && rs.next()) {

            SpoBinaryDTO dto = new SpoBinaryDTO(rs.getLong("SUBJECT"));
            dto.setContentType(rs.getString("DATATYPE"));
            dto.setLanguage(rs.getString("OBJ_LANG"));
            dto.setMustEmbed(YesNoBoolean.parse(rs.getString("MUST_EMBED")));

            return dto;
        }
    } catch (SQLException e) {
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(rs);
        SQLUtil.close(stmt);
        SQLUtil.close(conn);
    }

    return null;
}