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.grayfox.server.dao.jdbc.RecommendationJdbcDao.java

@Override
public List<Recommendation> findNearestByCategoriesLikedByFriends(String accessToken, Location location,
        Integer radius, Locale locale) {
    Set<String> categoryNames = new HashSet<>();
    List<Recommendation> recommendations = getJdbcTemplate().query(
            getQuery("Recommendation.findNearestByCategoriesLikedByFriends", locale), (ResultSet rs, int i) -> {
                String categoryName = rs.getString(9);
                if (categoryNames.add(categoryName)) {
                    Recommendation recommendation = new Recommendation();
                    Poi poi = new Poi();
                    int columnIndex = 1;
                    poi.setId(rs.getLong(columnIndex++));
                    poi.setName(rs.getString(columnIndex++));
                    poi.setLocation(new Location());
                    poi.getLocation().setLatitude(rs.getDouble(columnIndex++));
                    poi.getLocation().setLongitude(rs.getDouble(columnIndex++));
                    poi.setFoursquareId(rs.getString(columnIndex++));
                    poi.setFoursquareRating(rs.getDouble(columnIndex++));
                    recommendation.setType(Recommendation.Type.SOCIAL);
                    String friendFirstName = rs.getString(columnIndex++);
                    String friendLastName = rs.getString(columnIndex++);
                    String friendFullName = friendLastName == null || friendLastName.trim().isEmpty()
                            ? friendFirstName
                            : friendFirstName + " " + friendLastName;
                    recommendation.setReason(
                            Messages.get("recommendation.social.reason", locale, friendFullName, categoryName));
                    recommendation.setPoi(poi);
                    return recommendation;
                } else
                    return null;
            }, accessToken, location.getLatitude(), location.getLongitude(), radius);
    recommendations = recommendations.stream().filter(Objects::nonNull).collect(Collectors.toList());
    recommendations.forEach(recommendation -> recommendation.getPoi().setCategories(new HashSet<>(
            categoryDao.findByPoiFoursquareId(recommendation.getPoi().getFoursquareId(), locale))));
    return recommendations;
}

From source file:online.themixhub.demo.sql.impl.JobMapper.java

public Job mapRow(ResultSet rs, int rowNum) throws SQLException {
    Job job = new Job();
    job.setId(rs.getInt("id"));
    job.setOwner_id(rs.getInt("owner_id"));
    job.setEngineer_id(rs.getInt("engineer_id"));
    job.setTitle(rs.getString("title"));
    job.setDate(rs.getLong("date"));
    job.setStage(rs.getInt("stage"));
    job.setAnonymous_engineer(rs.getInt("anonymous_engineer"));
    job.setLast_activity_date(rs.getLong("last_activity_date"));
    return job;//from  ww w.  jav a  2s  . co m
}

From source file:io.cloudslang.engine.queue.repositories.ExecutionQueueRepositoryImpl.java

@Override
public Map<Long, Payload> findPayloadByExecutionIds(Long... ids) {
    String qMarks = StringUtils.repeat("?", ",", ids.length);
    String sqlStat = QUERY_PAYLOAD_BY_EXECUTION_IDS.replace(":IDS", qMarks);

    final Map<Long, Payload> result = new HashMap<>();
    findPayloadByExecutionIdsJDBCTemplate.query(sqlStat, ids, new RowCallbackHandler() {
        @Override/*www. j a  v a2s  .  c  o  m*/
        public void processRow(ResultSet resultSet) throws SQLException {
            result.put(resultSet.getLong(1), new Payload(resultSet.getBytes("payload")));
        }
    });

    return result;
}

From source file:com.flexive.ejb.beans.HistoryTrackerEngineBean.java

/**
 * {@inheritDoc}/*from  w w w.  ja  v  a  2 s. co  m*/
 */
@Override
public List<FxHistory> getContentEntries(long contentId) {
    List<FxHistory> ret = new ArrayList<FxHistory>(100);
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement(
                StorageManager.escapeReservedWords(HISTORY_SELECT) + " WHERE PKID=? ORDER BY TIMESTP");
        ps.setLong(1, contentId);
        ResultSet rs = ps.executeQuery();
        boolean loadData = FxContext.getUserTicket().isGlobalSupervisor();
        while (rs != null && rs.next())
            ret.add(new FxHistory(rs.getLong(3), rs.getLong(1), rs.getString(2), rs.getString(4),
                    rs.getString(5).split("\\|"), rs.getLong(8), rs.getLong(9), rs.getInt(10), rs.getString(6),
                    rs.getString(7), loadData ? rs.getString(11) : "No permission to load to data!",
                    rs.getString(12)));
    } catch (Exception ex) {
        LOG.error(ex.getMessage());
    } finally {
        Database.closeObjects(HistoryTrackerEngineBean.class, con, ps);
    }
    return ret;
}

From source file:net.mindengine.oculus.frontend.service.issue.JdbcIssueDAO.java

@Override
public long createIssue(Issue issue) throws Exception {
    PreparedStatement ps = getConnection().prepareStatement(
            "insert into issues (name, link, summary, description, author_id, date, fixed, fixed_date, project_id, subproject_id) "
                    + "values (?,?,?,?,?,?,?,?,?,?)");

    ps.setString(1, issue.getName());//from   w w  w . j a v a  2  s . co m
    ps.setString(2, issue.getLink());
    ps.setString(3, issue.getSummary());
    ps.setString(4, issue.getDescription());
    ps.setLong(5, issue.getAuthorId());
    ps.setTimestamp(6, new Timestamp(issue.getDate().getTime()));
    ps.setInt(7, issue.getFixed());
    ps.setTimestamp(8, new Timestamp(issue.getFixedDate().getTime()));
    ps.setLong(9, issue.getProjectId());
    ps.setLong(10, issue.getSubProjectId());

    logger.info(ps);

    ps.execute();

    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
        return rs.getLong(1);
    }
    return 0;
}

From source file:com.apbc.dao.AgentPayablesDAO.java

public List<ExtractedAgentPaymentSummary> getPayablesTotalRow(PayPeriod pp, final KnownAgentDAO agent,
        final AgentLicenceDAO lic) {
    Date d1 = pp.getFromDate();//from   w w w.j a  v  a2s . c o  m
    Date d2 = pp.getToDate();

    String datequeryPart = " where payment_date BETWEEN CAST('" + d1 + "'" + " AS DATE) and CAST('" + d2 + "' "
            + "AS DATE)";

    String query = "select   agent_id,transaction_type, creation_date,"
            + "(select sum(agent_earned_commission)    from asbckodbnew.agent_payables" + datequeryPart
            + "   and transaction_type= " + 1 + "   and agent_id = p1.agent_id"
            + "   group by agent_id      )as 'normal',"
            + "(select sum(agent_earned_commission)       from asbckodbnew.agent_payables" + datequeryPart
            + "   and transaction_type= " + 2
            + "      and agent_id = p1.agent_id      group by agent_id      )as 'chargeback'," +

            "(select sum(agent_earned_commission)       from asbckodbnew.agent_payables" + datequeryPart
            + "   and transaction_type= " + 3
            + "      and agent_id = p1.agent_id      group by agent_id      )as 'adjustments',"
            + "   (select sum(agent_earned_commission)    from asbckodbnew.agent_payables" + datequeryPart
            + "   and agent_id = p1.agent_id    group by agent_id) as 'allTotal'"
            + "   from asbckodbnew.agent_payables p1       " + datequeryPart + "group by agent_id";

    final Date d3 = pp.getUptoExtractDate();
    final Integer payperiodid = Integer.valueOf(pp.getPayperiodId());
    return template.query(query,

            new RowMapper<ExtractedAgentPaymentSummary>() {
                @Override
                public ExtractedAgentPaymentSummary mapRow(ResultSet rs, int rownumber) throws SQLException {
                    ExtractedAgentPaymentSummary e = new ExtractedAgentPaymentSummary();
                    e.setAgent_id(rs.getInt("agent_id"));
                    e.setPayadjustments(rs.getLong("adjustments"));
                    e.setPaynormal(rs.getLong("normal"));
                    e.setPaychargeback(rs.getLong("chargeback"));
                    e.setPaymenttotal(rs.getLong("allTotal"));
                    e.setPayperiod(payperiodid);
                    e.setAgent_name(getAgentName(agent, rs.getInt("agent_id"))); // AGENT NAME TO QUERY FROM AGENT TABLE...BY USING AGENT_ID
                    e.setPayperiodupto(d3);
                    e.setCreationdate(rs.getDate("creation_date"));
                    return e;
                }
            });
}

From source file:com.silverpeas.gallery.dao.MediaDAO.java

/**
 * Adding all data of videos./*from   w  w  w .  jav a2 s .c o m*/
 * @param con
 * @param media
 * @param videos
 * @throws SQLException
 */
private static void decorateVideos(final Connection con, List<Media> media, Map<String, Video> videos)
        throws SQLException {
    if (!videos.isEmpty()) {
        Collection<Collection<String>> idGroups = CollectionUtil.split(new ArrayList<String>(videos.keySet()));
        StringBuilder queryBase = new StringBuilder(SELECT_INTERNAL_MEDIA_PREFIX)
                .append("V.resolutionW, V.resolutionH, V.bitrate, V.duration from SC_Gallery_Internal I join "
                        + "SC_Gallery_Video V on I.mediaId = V.mediaId where I.mediaId in ");
        for (Collection<String> mediaIds : idGroups) {
            PreparedStatement prepStmt = null;
            ResultSet rs = null;
            try {
                prepStmt = con.prepareStatement(DBUtil.appendListOfParameters(queryBase, mediaIds).toString());
                DBUtil.setParameters(prepStmt, mediaIds);
                rs = prepStmt.executeQuery();
                while (rs.next()) {
                    String mediaId = rs.getString(1);
                    mediaIds.remove(mediaId);
                    Video currentVideo = videos.get(mediaId);
                    decorateInternalMedia(rs, currentVideo);
                    currentVideo.setDefinition(Definition.of(rs.getInt(8), rs.getInt(9)));
                    currentVideo.setBitrate(rs.getLong(10));
                    currentVideo.setDuration(rs.getLong(11));
                }
            } finally {
                DBUtil.close(rs, prepStmt);
            }
            // Not found
            for (String mediaIdNotFound : mediaIds) {
                Video currentVideo = videos.remove(mediaIdNotFound);
                media.remove(currentVideo);
                SilverTrace.warn(GalleryComponentSettings.COMPONENT_NAME, "MediaDAO.decorateVideos()",
                        "root.MSG_GEN_PARAM_VALUE",
                        "video not found (removed from result): " + mediaIdNotFound);
            }
        }
    }
}

From source file:br.bookmark.db.util.ResultSetUtils.java

/**
 * Map JDBC objects to Java equivalents.
 * Used by getBean() and getBeans()./*from ww  w. j  a v a 2s. c om*/
 * <p>
 * Some types not supported.
 * Many not work with all drivers.
 * <p>
 * Makes binary conversions of BIGINT, DATE, DECIMAL, DOUBLE, FLOAT, INTEGER,
 * REAL, SMALLINT, TIME, TIMESTAMP, TINYINT.
 * Makes Sting conversions of CHAR, CLOB, VARCHAR, LONGVARCHAR, BLOB, LONGVARBINARY,
 * VARBINARY.
 * <p>
 * DECIMAL, INTEGER, SMALLINT, TIMESTAMP, CHAR, VARCHAR tested with MySQL and Poolman.
 * Others not guaranteed.
 * @param classeDestino 
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 */
private static void putEntry(Map properties, ResultSetMetaData metaData, ResultSet resultSet, int i,
        Class classeDestino) throws Exception {

    /*
    In a perfect universe, this would be enough
    properties.put(
        metaData.getColumnName(i),
        resultSet.getObject(i));
    But only String, Timestamp, and Integer seem to get through that way.
    */

    String columnName = metaData.getColumnName(i);

    // Testa se  uma FK
    /*Field[] fields = classeDestino.getDeclaredFields();
    for (int j = 0; j < fields.length; j++) {
    if (fields[j].getAnnotation(DBFK.class) != null) {
        properties.put(columnName, resultSet.getString(i));
    }
    }*/
    //System.out.println(i+"-"+metaData.getColumnType(i));
    switch (metaData.getColumnType(i)) {

    // http://java.sun.com/j2se/1.3.0/docs/api/java/sql/Types.html

    case Types.BIGINT:
        properties.put(columnName, new Long(resultSet.getLong(i)));
        break;

    case Types.DATE:
        properties.put(columnName, resultSet.getDate(i));
        break;

    case Types.DECIMAL:
    case Types.DOUBLE:
        properties.put(columnName, new Double(resultSet.getDouble(i)));
        break;

    case Types.FLOAT:
        properties.put(columnName, new Float(resultSet.getFloat(i)));
        break;

    case Types.INTEGER:
        int valor = 0;
        try { // Se o campo esta vazio d erro
            valor = resultSet.getInt(i);
        } catch (SQLException e) {
        }
        properties.put(columnName, new Integer(valor));
        break;

    case Types.REAL:
        properties.put(columnName, new Double(resultSet.getString(i)));
        break;

    case Types.SMALLINT:
        properties.put(columnName, new Short(resultSet.getShort(i)));
        break;

    case Types.TIME:
        properties.put(columnName, resultSet.getTime(i));
        break;

    case Types.TIMESTAMP:
        properties.put(columnName, resultSet.getTimestamp(i));
        break;

    // :FIXME: Throws java.lang.ClassCastException: java.lang.Integer
    // :FIXME: with Poolman and MySQL unless use getString.
    case Types.TINYINT:
        properties.put(columnName, new Byte(resultSet.getString(i)));
        break;

    case Types.CHAR:
    case Types.CLOB:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        // :FIXME: Handle binaries differently?
    case Types.BLOB:
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
        properties.put(columnName, resultSet.getString(i));
        break;

    /*
        :FIXME: Add handlers for
        ARRAY
        BINARY
        BIT
        DISTINCT
        JAVA_OBJECT
        NULL
        NUMERIC
        OTHER
        REF
        STRUCT
    */

    // Otherwise, pass as *String property to be converted
    default:
        properties.put(columnName + "String", resultSet.getString(i));
        break;
    } // end switch

}

From source file:net.solarnetwork.node.dao.jdbc.reactor.JdbcInstructionDao.java

private List<Instruction> extractInstructions(ResultSet rs) throws SQLException {
    List<Instruction> results = new ArrayList<Instruction>(5);
    BasicInstruction bi = null;/*from  w ww .java  2 s .com*/
    while (rs.next()) {
        long currId = rs.getLong(1);
        if (bi == null || bi.getId().longValue() != currId) {
            InstructionStatus status = new BasicInstructionStatus(currId,
                    InstructionState.valueOf(rs.getString(6)), rs.getTimestamp(7),
                    (rs.getString(8) == null ? null : InstructionState.valueOf(rs.getString(8))));
            bi = new BasicInstruction(currId, rs.getString(2), rs.getTimestamp(3), rs.getString(4),
                    rs.getString(5), status);
            results.add(bi);
        }
        String pName = rs.getString(9);
        String pValue = rs.getString(10);
        if (pName != null) {
            bi.addParameter(pName, pValue);
        }
    }
    return results;
}

From source file:de.ingrid.importer.udk.strategy.v33.IDCStrategy3_3_0_a.java

private void migrateT02AddressDescr() throws Exception {
    log.info("\nMigrate data from 't02_address.descr' to 'address_comment'...");

    // NOTICE: We do NOT update search index due to same values.

    // select all data from old tables
    String sqlSelectOldData = "SELECT id, descr " + "FROM t02_address " + "WHERE descr IS NOT NULL "
            + "ORDER BY id";

    // read current max line column of address
    PreparedStatement psSelectCommentLine = jdbc.prepareStatement(
            "SELECT line " + "FROM address_comment " + "WHERE addr_id = ? " + "ORDER BY line DESC");

    // insert into comment table
    PreparedStatement psInsert = jdbc.prepareStatement("INSERT INTO address_comment "
            + "(id, addr_id, comment_, create_uuid, create_time , line) " + "VALUES (?,?,?,?,?,?)");

    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery(sqlSelectOldData, st);
    int numProcessed = 0;
    String prefix = "[Dieser Eintrag wurde automatisch aus dem Feld Notiz berfhrt.]\n";
    String catAdminUuid = getCatalogAdminUuid();
    while (rs.next()) {

        long addrId = rs.getLong("id");
        String addrNote = rs.getString("descr");

        if (addrNote != null && addrNote.trim().length() > 0) {
            // read current max line column of address comments
            int lineValue = 1;
            psSelectCommentLine.setLong(1, addrId);
            ResultSet rsLine = psSelectCommentLine.executeQuery();
            if (rsLine.next()) {
                lineValue = rsLine.getInt("line") + 1;
            }/*from   www .  j av a 2 s.  c  o  m*/
            rsLine.close();

            psInsert.setLong(1, getNextId());
            psInsert.setLong(2, addrId);
            psInsert.setString(3, prefix + addrNote);
            psInsert.setString(4, catAdminUuid);
            String now = dateToTimestamp(new Date());
            psInsert.setString(5, now);
            psInsert.setInt(6, lineValue);
            psInsert.executeUpdate();

            numProcessed++;
            log.debug("Transferred entry from 't02_address.descr' to 'address_comment': " + "addrId=" + addrId
                    + " -> " + addrNote + "/" + catAdminUuid + "/" + now + "/" + lineValue);
        }
    }
    rs.close();
    st.close();
    psSelectCommentLine.close();
    psInsert.close();

    log.info("Transferred " + numProcessed + " entries.");
    log.info("Migrate data from 't02_address.descr' to 'address_comment'... done\n");
}