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:de.swm.nis.logicaldecoding.dataaccess.ChangeSetFetcher.java

public List<ChangeSetDAO> fetch(String slotname, int maxRows) {

    RowMapper<ChangeSetDAO> changeSetRowMapper = new RowMapper<ChangeSetDAO>() {

        @Override/* w  w w .  j  ava  2  s.  c  o m*/
        public ChangeSetDAO mapRow(ResultSet rs, int rowNum) throws SQLException {
            ChangeSetDAO changeset = new ChangeSetDAO();
            changeset.setData(rs.getString("data"));
            changeset.setLocation(rs.getString("location"));
            changeset.setTransactionId(rs.getLong("xid"));
            return changeset;
        }
    };

    //Parameter 1: replication Slot name
    //Parameter 2: upto_n_changes
    String sql = "SELECT * from pg_logical_slot_get_changes(?, NULL, ?, 'include-timestamp', 'on')";
    List<ChangeSetDAO> changes = template.query(sql, new Object[] { slotname, maxRows }, changeSetRowMapper);
    return changes;
}

From source file:com.webproject.checkpoint.DataRepository.java

public Examine getExamine(String examineSerialNumber) {
    return dbt.query(
            "SELECT SERIALNUMBER, NUMBEROFCHALLENGE, TIMEINMILLISECOND FROM EXAMINEREPOSITORY WHERE SERIALNUMBER=?",
            new Object[] { examineSerialNumber }, (ResultSet rs) -> {
                Examine examine = new Examine();
                while (rs.next()) {
                    String examineClass = rs.getString(1);
                    int numberOfChallenge = rs.getInt(2);
                    long timeInMillisecond = rs.getLong(3);
                    examine.setExamineClass(examineClass);
                    examine.setNumberOfChallenge(numberOfChallenge);
                    examine.setTimeInMillisecond(timeInMillisecond);
                }/*  www.  ja  v a2 s  . c om*/
                return examine;
            });
}

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

protected void updateObjectUse() throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Updating object_use...");
    }//from w  ww  . j a va  2s  .c o m

    if (log.isInfoEnabled()) {
        log.info("Migrate object_access.terms_of_use to table object_use...");
    }

    String sql = "select object_access.obj_id, object_access.line, object_access.terms_of_use "
            + "from object_access";

    // Node may contain multiple equal entries for same object ! 
    // we track written data in hash maps to avoid multiple writing for same object
    HashMap<Long, List<String>> processedObjIds = new HashMap<Long, List<String>>();

    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery(sql, st);
    int numMigrated = 0;
    while (rs.next()) {
        long objId = rs.getLong("obj_id");
        int line = rs.getInt("line");
        String termsOfUse = rs.getString("terms_of_use");
        termsOfUse = (termsOfUse == null) ? "" : termsOfUse.trim();

        // check whether value already written
        boolean writeNewValue = false;
        if (termsOfUse.length() > 0) {
            List<String> valueList = processedObjIds.get(objId);
            if (valueList == null) {
                valueList = new ArrayList<String>();
                processedObjIds.put(objId, valueList);
            }
            if (!valueList.contains(termsOfUse)) {
                writeNewValue = true;
            }
        }

        // write value if not written yet !
        if (writeNewValue) {
            jdbc.executeUpdate("INSERT INTO object_use (id, obj_id, line, terms_of_use) " + "VALUES ("
                    + getNextId() + ", " + objId + ", " + line + ", '" + termsOfUse + "')");

            if (log.isDebugEnabled()) {
                log.debug("object_use: migrated (obj_id, line, terms_of_use) (" + objId + ", " + line + ", '"
                        + termsOfUse + "')");
            }

            List<String> valueList = processedObjIds.get(objId);
            valueList.add(termsOfUse);
            numMigrated++;

            // extend object index (index contains only data of working versions !)
            // Not necessary, contents are the same ! just restructured !
        }
    }
    rs.close();
    st.close();

    if (log.isInfoEnabled()) {
        log.info("Migrated " + numMigrated + " terms_of_use from table object_access to new table object_use");
    }

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

From source file:net.riezebos.thoth.content.comments.dao.CommentDao.java

protected Comment setComment(ResultSet rs) throws SQLException {
    Comment comment = new Comment();
    int idx = 1;//from  w  w w. jav a  2s.co  m
    comment.setId(rs.getLong(idx++));
    comment.setUserName(rs.getString(idx++));
    comment.setContextName(rs.getString(idx++));
    comment.setDocumentPath(rs.getString(idx++));
    comment.setTimeCreated(rs.getTimestamp(idx++));
    comment.setTitle(rs.getString(idx++));
    comment.setDao(this);
    return comment;
}

From source file:com.haulmont.cuba.core.app.UniqueNumbers.java

protected Object executeScript(String domain, String sqlScript) {
    EntityManager em = persistence.getEntityManager(getDataStore(domain));
    StrTokenizer tokenizer = new StrTokenizer(sqlScript, SequenceSupport.SQL_DELIMITER);
    Object value = null;/*from  w  w w.  j  a va2  s.com*/
    Connection connection = em.getConnection();
    while (tokenizer.hasNext()) {
        String sql = tokenizer.nextToken();
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            try {
                if (statement.execute()) {
                    ResultSet rs = statement.getResultSet();
                    if (rs.next())
                        value = rs.getLong(1);
                }
            } finally {
                DbUtils.closeQuietly(statement);
            }
        } catch (SQLException e) {
            throw new IllegalStateException("Error executing SQL for getting next number", e);
        }
    }
    return value;
}

From source file:com.mtgi.analytics.sql.BehaviorTrackingDataSourceTest.java

@Test
public void testStaticSql() throws Exception {
    //test simple static insert / update.
    assertFalse(stmt.execute("insert into TEST_TRACKING values (1, 'hello', null)"));

    //test batching.  each batch should create one event.
    stmt.addBatch("insert into TEST_TRACKING values (3, 'batch', '1')");
    stmt.addBatch("insert into TEST_TRACKING values (4, 'batch', '2')");
    stmt.executeBatch();//from w w  w.j  a v a2  s.  c  o m

    assertFalse(stmt.execute("insert into TEST_TRACKING values (2, 'goodbye', null)"));
    assertEquals(4, stmt.executeUpdate("update TEST_TRACKING set DESCRIPTION = 'world'"));

    //test query.
    ResultSet rs = stmt.executeQuery("select ID from TEST_TRACKING order by ID");
    int index = 0;
    long[] keys = { 1L, 2L, 3L, 4L };
    while (rs.next())
        assertEquals(keys[index++], rs.getLong(1));
    rs.close();
    assertEquals(4, index);

    manager.flush();
    assertEventDataMatches("BehaviorTrackingDataSourceTest.testStaticSql-result.xml");
}

From source file:com.ywang.alone.handler.task.AuthTask.java

/**
 * ? { 'key':'2597aa1d37d432a', 'pNo':'0' }
 * //  w  w  w  . j  a  va 2s. c o  m
 * @param param
 * @return
 */
private static String getAllFollows(String msg) {
    JSONObject jsonObject = AloneUtil.newRetJsonObject();
    JSONObject param = JSON.parseObject(msg);
    String token = param.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);
    } else {
        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);
            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);

            }
        }
        JedisUtil.returnJedis(jedis);
    }

    if (StringUtils.isEmpty(userId)) {
        return jsonObject.toJSONString();
    }

    LoggerUtil.logMsg("uid is " + userId);

    DruidPooledConnection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = DataSourceFactory.getInstance().getConn();
        conn.setAutoCommit(false);

        stmt = conn.prepareStatement(
                "SELECT * FROM USERBASE WHERE USER_ID IN (SELECT FOLLOWED_ID FROM FOLLOW WHERE USER_ID = ?)");
        stmt.setString(1, userId);

        ArrayList<UserInfo> followedList = new ArrayList<UserInfo>();
        UserInfo userInfo = null;
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {

            userInfo = new UserInfo();
            userInfo.setUserId(rs.getString("USER_ID"));
            userInfo.setAvatar(rs.getString("AVATAR"));
            userInfo.setNickName(rs.getString("NICKNAME"));
            userInfo.setAge(rs.getString("AGE"));
            userInfo.setRoleName(rs.getString("ROLENAME"));
            userInfo.setOnline(rs.getString("ONLINE"));
            userInfo.setLastLoginTime(rs.getLong("LAST_LOGIN_TIME"));
            userInfo.setIntro(rs.getString("INTRO"));
            userInfo.setDistance(rs.getString("DISTANCE"));

            followedList.add(userInfo);
        }

        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.ErrorDesc.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:com.ex.Dao.impl.GroupDaoImpl.java

@Override
public Group findGroupById(String id) {
    String sql = "SELECT * FROM " + dbName + " WHERE GROUP_ID = '" + id + "'";
    return jdbcTemplate.query(sql, new ResultSetExtractor<Group>() {
        @Override//from w  ww  .j a  va2  s.c  o  m
        public Group extractData(ResultSet rs) throws SQLException, DataAccessException {
            if (rs.next()) {
                Group group = new Group();
                group.setId(rs.getString("group_id"));
                group.setVersion(rs.getLong("version"));
                group.setXml(rs.getString("xml"));
                group.setGroupName(rs.getString("group_name"));
                group.setCreatedBy(rs.getString("created_by"));
                group.setUpdatedAt(rs.getTimestamp("updated_at"));
                return group;
            }

            return null;
        }
    });
}

From source file:org.psystems.dicom.browser.server.stat.UseagStoreChartServlet.java

public JFreeChart getChart() {

    PreparedStatement psSelect = null;

    try {// w ww . j  a  va2  s .  c o  m

        Connection connection = Util.getConnection("main", getServletContext());
        long dcmSizes = 0;
        long imgSizes = 0;
        //
        // ALL_IMAGE_SIZE
        // ALL_DCM_SIZE

        // psSelect = connection
        // .prepareStatement("SELECT ID, METRIC_NAME, METRIC_DATE, METRIC_VALUE_LONG "
        // + " FROM WEBDICOM.DAYSTAT WHERE METRIC_NAME = ?");

        psSelect = connection.prepareStatement(
                "SELECT SUM(METRIC_VALUE_LONG) S " + " FROM WEBDICOM.DAYSTAT WHERE METRIC_NAME = ?");

        psSelect.setString(1, "ALL_DCM_SIZE");
        ResultSet rs = psSelect.executeQuery();
        while (rs.next()) {
            dcmSizes = rs.getLong("S");
        }
        rs.close();

        psSelect.setString(1, "ALL_IMAGE_SIZE");
        rs = psSelect.executeQuery();
        while (rs.next()) {
            imgSizes = rs.getLong("S");
        }
        rs.close();

        String dcmRootDir = getServletContext().getInitParameter("webdicom.dir.src");
        long totalSize = new File(dcmRootDir).getTotalSpace(); //TODO !
        long freeSize = new File(dcmRootDir).getFreeSpace();
        long busySize = totalSize - freeSize;

        //         System.out.println("!!! totalSize=" + totalSize + " freeSize="+freeSize);

        long diskEmpty = freeSize - imgSizes - dcmSizes;

        //         double KdiskEmpty = (double)diskEmpty/(double)totalSize;
        //         System.out.println("!!! " + KdiskEmpty);

        double KdiskBusi = (double) busySize / (double) totalSize * 100;
        //         System.out.println("!!! KdiskBusi=" + KdiskBusi);

        double KdcmSizes = (double) dcmSizes / (double) totalSize * 100;
        //         System.out.println("!!! KdcmSizes=" + KdcmSizes);

        double KimgSizes = (double) imgSizes / (double) totalSize * 100;
        //         System.out.println("!!! KimgSizes=" + KimgSizes);

        double KdiskFree = (double) freeSize / (double) (totalSize - KdcmSizes - KimgSizes) * 100;
        //         System.out.println("!!! KdiskFree=" + KdiskFree);

        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("??? (DCM-) " + dcmSizes / 1000 + " .", KdcmSizes);
        dataset.setValue("? (JPG-) " + imgSizes / 1000 + " .", KimgSizes);
        dataset.setValue("?  " + busySize / 1000 + " .", KdiskBusi);
        dataset.setValue(" " + freeSize / 1000 + " .", KdiskFree);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        JFreeChart chart = ChartFactory.createPieChart(
                "? ? ??  ?",
                dataset, legend, tooltips, urls);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        // chart.setBorderVisible(true);
        // chart.setPadding(new RectangleInsets(20 ,20,20,20));

        return chart;

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

        try {
            if (psSelect != null)
                psSelect.close();
        } catch (SQLException e) {
            logger.error(e);
        }
    }
    return null;

}

From source file:com.ex.Dao.impl.GroupDaoImpl.java

@Override
public Group findGroupByName(String name) {
    String sql = "SELECT * FROM " + dbName + " WHERE GROUP_NAME = '" + name + "'";
    return jdbcTemplate.query(sql, new ResultSetExtractor<Group>() {
        @Override// w ww .  java  2 s . c  o  m
        public Group extractData(ResultSet rs) throws SQLException, DataAccessException {
            if (rs.next()) {
                Group group = new Group();
                group.setId(rs.getString("group_id"));
                group.setVersion(rs.getLong("version"));
                group.setXml(rs.getString("xml"));
                group.setGroupName(rs.getString("group_name"));
                group.setCreatedBy(rs.getString("created_by"));
                group.setUpdatedAt(rs.getTimestamp("updated_at"));
                return group;
            }

            return null;
        }

    });
}