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.ywang.alone.handler.task.AuthTask.java

/**
 * /*from  w w  w. j a  v a2  s  .  co  m*/
 * 
 * @param param
 *            <pre>
 *    {
 *    'key':'2597aa1d37d432a','lng':'117.157954','lat':'31.873432','currPage':'1','pageSize':'50' 
 *    }
 * </pre>
 * 
 * @return 
 */
private static String nearby(String msg) {
    JSONObject jsonObject = AloneUtil.newRetJsonObject();
    JSONObject user = JSON.parseObject(msg);

    String token = user.getString("key");
    String userId = null;
    if (StringUtils.isEmpty(token)) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
        return jsonObject.toJSONString();
    }

    Jedis jedis = JedisUtil.getJedis();
    Long tokenTtl = jedis.ttl("TOKEN:" + token);
    if (tokenTtl == -1) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
    } else {
        userId = jedis.get("TOKEN:" + token);
        LoggerUtil.logMsg("uid is " + userId);
    }

    JedisUtil.returnJedis(jedis);

    if (StringUtils.isEmpty(userId)) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
        return jsonObject.toJSONString();
    }

    DruidPooledConnection conn = null;
    PreparedStatement stmt = null;
    try {

        conn = DataSourceFactory.getInstance().getConn();
        conn.setAutoCommit(false);

        // TODO ?column ?
        stmt = conn.prepareStatement(
                "SELECT USER_ID,AVATAR,NICKNAME,AGE,ROLENAME,`ONLINE`,LAST_LOGIN_TIME,INTRO, MESSAGE_USER,"
                        + "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((? * PI()/180-lat * PI()/180)/2),2) +"
                        + " COS(? * PI()/180) * COS(lat * PI()/180) * POW(SIN((? * PI()/180-lng * PI()/180)/2),2))) * 1000) "
                        + " AS  DISTANCE " + "FROM userbase WHERE USER_ID <> ? ORDER BY distance LIMIT ?,?");
        stmt.setString(1, user.getString("lat"));
        stmt.setString(2, user.getString("lat"));
        stmt.setString(3, user.getString("lng"));
        stmt.setString(4, userId);
        stmt.setInt(5, Integer.valueOf(user.getString("currPage")));
        stmt.setInt(6, Integer.valueOf(user.getString("pageSize")));

        JSONArray nearbyUserArray = new JSONArray();
        UserInfo userInfo = null;
        ResultSet nearbyRs = stmt.executeQuery();
        while (nearbyRs.next()) {

            userInfo = new UserInfo();
            userInfo.setUserId(nearbyRs.getString("USER_ID"));
            userInfo.setAvatar(nearbyRs.getString("AVATAR"));
            userInfo.setNickName(nearbyRs.getString("NICKNAME"));
            userInfo.setAge(nearbyRs.getString("AGE"));
            userInfo.setRoleName(nearbyRs.getString("ROLENAME"));
            userInfo.setOnline(nearbyRs.getString("ONLINE"));
            userInfo.setLastLoginTime(nearbyRs.getLong("LAST_LOGIN_TIME"));
            userInfo.setIntro(nearbyRs.getString("INTRO"));
            userInfo.setDistance(nearbyRs.getString("DISTANCE"));
            userInfo.setMessageUser(nearbyRs.getString("MESSAGE_USER"));
            nearbyUserArray.add(userInfo);
        }
        jsonObject.put("data", nearbyUserArray);
        nearbyRs.close();

        conn.commit();
        conn.setAutoCommit(true);
    } catch (SQLException e) {
        LoggerUtil.logServerErr(e);
        jsonObject.put("ret", Constant.RET.SYS_ERR);
        jsonObject.put("errCode", Constant.ErrorCode.SYS_ERR);
        jsonObject.put("errDesc", Constant.ErrorCode.SYS_ERR);
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
            if (null != conn) {
                conn.close();
            }
        } catch (SQLException e) {
            LoggerUtil.logServerErr(e.getMessage());
        }
    }

    return jsonObject.toJSONString();
}

From source file:me.j360.idgen.impl.SequenceIdGenServiceImpl.java

/**
 * Gets the next id as a long. This method will only be called when
 * synchronized and when the data type is configured to be long.
 * // w  w  w  .jav a  2 s.c  o m
 * @return the next id as a long.
 * @throws IdCreationException
 */
protected long getNextLongIdInner() {
    getLogger().debug("[IDGeneration Service] Requesting an Id using query: {}", query);

    try {
        // 2009.10.08 - without handling connection directly
        Connection conn = DataSourceUtils.getConnection(getDataSource());
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.prepareStatement(query);
            rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getLong(1);
            } else {
                getLogger().error(
                        "[IDGeneration Service] Unable to allocate a block of Ids. Query for Id did not return a value.");
                throw new IdCreationException(
                        "[IDGeneration Service] Unable to allocate a block of Ids. Query for Id did not return a value.");
            }
        } finally {
            if (rs != null) {
                JdbcUtils.closeResultSet(rs);
            }
            if (stmt != null) {
                JdbcUtils.closeStatement(stmt);
            }
            // 2009.10.08 - without handling connection directly
            if (conn != null) {
                DataSourceUtils.releaseConnection(conn, getDataSource());
            }
        }
        // 2009.10.08 - without handling connection directly
    } catch (Exception ex) {
        if (ex instanceof IdCreationException)
            throw (IdCreationException) ex;
        getLogger().error(
                "[IDGeneration Service] We can't get a connection. So, unable to allocate a block of Ids.", ex);
        throw new IdCreationException(
                "[IDGeneration Service] We can't get a connection. So, unable to allocate a block of Ids.", ex);
    }
}

From source file:com.dsf.dbxtract.cdc.AppJournalWindowTest.java

/**
 * Rigourous Test :-)/*  w  w  w .j  a  va2 s  .c o m*/
 * 
 * @throws Exception
 *             in case of any error
 */
@Test(dependsOnMethods = "setUp", timeOut = 120000)
public void testAppWithJournalWindow() throws Exception {

    final Config config = new Config(configFile);

    BasicDataSource ds = new BasicDataSource();
    Source source = config.getDataSources().getSources().get(0);
    ds.setDriverClassName(source.getDriver());
    ds.setUsername(source.getUser());
    ds.setPassword(source.getPassword());
    ds.setUrl(source.getConnection());

    // prepara os dados
    Connection conn = ds.getConnection();

    conn.createStatement().execute("truncate table test");
    conn.createStatement().execute("truncate table j$test");

    // Carrega os dados de origem
    PreparedStatement ps = conn.prepareStatement("insert into test (key1,key2,data) values (?,?,?)");
    for (int i = 0; i < TEST_SIZE; i++) {
        if ((i % 100) == 0) {
            ps.executeBatch();
        }
        ps.setInt(1, i);
        ps.setInt(2, i);
        ps.setInt(3, (int) Math.random() * 500);
        ps.addBatch();
    }
    ps.executeBatch();
    ps.close();

    // Popula as tabelas de journal
    ps = conn.prepareStatement("insert into j$test (key1,key2) values (?,?)");
    for (int i = 0; i < TEST_SIZE; i++) {
        if ((i % 500) == 0) {
            ps.executeBatch();
        }
        ps.setInt(1, i);
        ps.setInt(2, i);
        ps.addBatch();
    }
    ps.executeBatch();
    ps.close();

    Long maxWindowId = 0L;
    ResultSet rs = conn.createStatement().executeQuery("select max(window_id) from j$test");
    if (rs.next()) {
        maxWindowId = rs.getLong(1);
        System.out.println("maximum window_id loaded: " + maxWindowId);
    }
    rs.close();
    conn.close();
    ds.close();

    // Clear any previous test
    String zkKey = "/dbxtract/cdc/" + source.getName() + "/J$TEST/lastWindowId";
    if (client.checkExists().forPath(zkKey) != null)
        client.delete().forPath(zkKey);

    // starts monitor
    Monitor.getInstance(config);

    // start app
    app = new App(config);
    System.out.println(config.toString());
    app.start();

    Assert.assertEquals(config.getHandlers().iterator().next().getStrategy(), JournalStrategy.WINDOW);

    while (true) {
        TimeUnit.MILLISECONDS.sleep(500);

        try {
            Long lastWindowId = Long.parseLong(new String(client.getData().forPath(zkKey)));
            System.out.println("lastWindowId = " + lastWindowId);
            if (maxWindowId.longValue() == lastWindowId.longValue()) {
                System.out.println("expected window_id reached");
                break;
            }

        } catch (NoNodeException nne) {
            System.out.println("ZooKeeper - no node exception :: " + zkKey);
        }
    }
}

From source file:es.emergya.bbdd.dao.RoutingHome.java

/**
 * Devuelve la lista de ids de la ruta desde vertice_origen a
 * vertice_destino/* w ww .  j  a  v  a2  s .  co  m*/
 * 
 * @param origin
 * @param goal
 * @return
 */
@Transactional(readOnly = true, rollbackFor = Throwable.class)
private List<Long> getSimpleGid(final Long origin, final Long goal) {
    final List<Long> lista = new ArrayList<Long>();
    try {
        Session currentSession = getSession();
        CallableStatement consulta = currentSession.connection().prepareCall("{call shortest_path(?,?,?,?,?)}");
        consulta.setString(1, "SELECT id, " + source + "::int4, " + target + "::int4, " + "ST_length2d("
                + the_geom + ")::float8 as cost FROM " + table);
        consulta.setLong(2, origin);
        consulta.setLong(3, goal);
        consulta.setBoolean(4, false);
        consulta.setBoolean(5, false);
        log.trace(consulta);
        ResultSet resultado = consulta.executeQuery();

        while (resultado.next())
            lista.add(resultado.getLong("edge_id"));
    } catch (Exception e) {
        log.error("No se pudo calcular la ruta", e);
    }

    return lista;
}

From source file:com.flexive.core.storage.PostgreSQL.PostgreSQLSequencerStorage.java

/**
 * {@inheritDoc}/*from w ww .  ja v a  2  s  . c  om*/
 */
@Override
public long getCurrentId(FxSystemSequencer sequencer) throws FxApplicationException {
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement(SQL_GET_INFO + PG_SEQ_PREFIX + sequencer.getSequencerName());
        ResultSet rs = ps.executeQuery();
        if (rs != null && rs.next())
            return rs.getLong(2);
    } catch (SQLException exc) {
        throw new FxDbException(LOG, exc, "ex.db.sqlError", exc.getMessage());
    } finally {
        Database.closeObjects(PostgreSQLSequencerStorage.class, con, ps);
    }
    throw new FxCreateException(LOG, "ex.sequencer.notFound", sequencer.getSequencerName());
}

From source file:com.alibaba.wasp.jdbc.TestJdbcConnectionPool.java

@Test
public void testGetConnection() throws SQLException {
    Connection conn = pool.getConnection();
    ResultSet rs;
    Statement stat = conn.createStatement();
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES (1, 79999, 'testGetConnection')");

    rs = stat.executeQuery("SELECT column1,column2 FROM test where column3='testGetConnection'");

    assertTrue(rs.next());//from   ww  w.  ja  v  a 2  s . c  om
    assertTrue(rs.getLong("column2") == 79999);
    conn.close();
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.dao.jdbc.BAMFileQueriesJDBCImpl.java

/**
 * init Bam lookup queries.//from w w  w .j  a v a 2s  .c  om
 */
@PostConstruct
protected void initBamLookupQueries() {
    bamDatatypeList = getJdbcTemplate().query(GET_BAM_DATATYPE, new ParameterizedRowMapper<BamDatatype>() {
        public BamDatatype mapRow(final ResultSet rs, final int i) throws SQLException {
            final BamDatatype dt = new BamDatatype();
            dt.setBamDatatypeId(rs.getLong(1));
            dt.setBamDatatype(rs.getString(2));
            dt.setGeneralDatatype(rs.getString(3));
            return dt;
        }
    });
    bamAliquotList = getJdbcTemplate().query(GET_SHIPPED_BIOSPECIMEN, new ParameterizedRowMapper<BamAliquot>() {
        public BamAliquot mapRow(final ResultSet rs, final int i) throws SQLException {
            final BamAliquot a = new BamAliquot();
            a.setAliquotId(rs.getLong(1));
            a.setUuid(rs.getString(2));
            return a;
        }
    });
    bamCGHubCenterList = getJdbcTemplate().query(GET_CGHUB_CENTER,
            new ParameterizedRowMapper<BamCGHubCenter>() {
                public BamCGHubCenter mapRow(final ResultSet rs, final int i) throws SQLException {
                    final BamCGHubCenter c = new BamCGHubCenter();
                    c.setCGHubCenter(rs.getString(1));
                    c.setCenterId(rs.getLong(2));
                    return c;
                }
            });
}

From source file:com.pactera.edg.am.metamanager.extractor.dao.helper.AuditMetadataMapper.java

public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
    AuditMetadata md = new AuditMetadata();
    md.setId(rs.getString("INSTANCE_ID"));
    md.setCode(rs.getString("INSTANCE_CODE"));
    md.setName(rs.getString("INSTANCE_NAME"));
    md.setClassifierId(rs.getString("CLASSIFIER_ID"));
    md.setNamespace(rs.getString("NAMESPACE"));
    md.setStartTime(rs.getLong("START_TIME"));
    md.setOperType(rs.getString("OPER_TYPE"));
    md.setDescription(rs.getString("DESCRIPTION"));

    MMMetadata parent = new MMMetadata();
    parent.setId(rs.getString("PARENT_ID"));
    md.setParentMetadata(parent);//from  ww w .  j  a  va 2 s.co m

    return md;
}

From source file:henu.dao.impl.CaclDaoImpl.java

@Override
public List<Cacl> getCacList(String uid) {
    String sql = "select * from cacl where author = " + uid;
    System.out.println(sql);//from w ww.ja va  2  s. co m

    ResultSet rs = SqlDB.executeQuery(sql);
    List<Cacl> list = new ArrayList<Cacl>();
    try {
        while (rs.next()) {
            Cacl cacl = new Cacl();
            cacl.setTid(rs.getLong("cid"));
            cacl.setName(rs.getString("cname"));
            cacl.setPostime(rs.getTimestamp("postime").toString());
            cacl.setStructure(rs.getString("structure"));
            cacl.setAuthor(Integer.parseInt(uid));
            cacl.setUsers(getCaclUserList(Long.toString(rs.getLong("cid"))));
            list.add(cacl);
        }
    } catch (SQLException ex) {

    }

    SqlDB.close();

    return list;
}

From source file:henu.dao.impl.CaclDaoImpl.java

@Override
public List<Cacl> getFormList(String uid) {
    String sql = "select * from cacl where cid in (select cid from uc where uid = " + uid + ")";
    System.out.println(sql);/*from ww  w  . j  av  a 2  s  .c o m*/

    ResultSet rs = SqlDB.executeQuery(sql);
    List<Cacl> list = new ArrayList<Cacl>();
    try {
        while (rs.next()) {
            Cacl table = new Cacl();
            table.setTid(rs.getLong("cid"));
            table.setAuthor(rs.getInt("author"));
            table.setName(rs.getString("cname"));
            table.setStructure(rs.getString("structure"));
            table.setPostime(rs.getTimestamp("postime").toString());
            list.add(table);
        }
    } catch (SQLException ex) {

    }

    SqlDB.close();

    return list;
}