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.flexive.core.storage.PostgreSQL.PostgreSQLSequencerStorage.java

private CustomSequencer loadCustomSequencer(Statement nonTxStatement, String name)
        throws SQLException, FxCreateException {
    // use non-transactional connection since the relation may have been deleted by another
    // thread, which would lead to a rollback on the main connection
    ResultSet rsi = null;
    try {//www . j  a  v  a 2  s . c o m
        rsi = nonTxStatement.executeQuery(SQL_GET_INFO + PG_SEQ_PREFIX + name);
        if (rsi.next()) {
            return new CustomSequencer(name, rsi.getBoolean(1), rsi.getLong(2));
        } else {
            throw new FxCreateException("ex.sequencer.notFound", name);
        }
    } catch (SQLException e) {
        throw new FxCreateException("ex.sequencer.notFound", name);
    } finally {
        if (rsi != null) {
            rsi.close();
        }
    }
}

From source file:com.splicemachine.derby.impl.load.HBaseBulkLoadIT.java

@Test
public void testComputeTableSplitKeys() throws Exception {
    if (notSupported)
        return;/* w  w w  .  ja  v  a  2s.c  o m*/
    String sql = " select conglomeratenumber from sys.systables t, sys.sysconglomerates c, sys.sysschemas s "
            + "where c.tableid=t.tableid and t.tablename='LINEITEM' and s.schemaid=c.schemaid and s.schemaname='%s' order by 1";

    ResultSet rs = methodWatcher.executeQuery(format(sql, SCHEMA_NAME));
    rs.next();
    long conglomId = rs.getLong(1);
    methodWatcher.execute(format(
            "call SYSCS_UTIL.COMPUTE_SPLIT_KEY('%s','%s',null,'L_ORDERKEY,L_LINENUMBER',"
                    + "'%s','|',null,null,null,null,-1,'/BAD',true,null,'%s')",
            SCHEMA_NAME, LINEITEM, getResource("lineitemKey.csv"), getResource("data")));
    rs.close();

    String select = "SELECT \"KEY\" " + "from new com.splicemachine.derby.vti.SpliceFileVTI("
            + "'%s',NULL,'|',NULL,'HH:mm:ss','yyyy-MM-dd','yyyy-MM-dd HH:mm:ss','true','UTF-8' ) "
            + "AS splitKey (\"KEY\" varchar(200))";
    rs = methodWatcher.executeQuery(format(select, getResource("data/" + conglomId + "/keys")));
    String s = TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs);
    String expected = "KEY     |\n" + "--------------\n" + "    \\x81     |\n" + "\\x81\\x00\\x83 |\n"
            + "\\x81\\x00\\x84 |\n" + "\\x81\\x00\\x85 |\n" + "\\x81\\x00\\x86 |\n" + "    \\x82     |\n"
            + "\\x82\\x00\\x81 |";

    Assert.assertEquals(expected, s);
}

From source file:com.splicemachine.derby.impl.load.HBaseBulkLoadIT.java

@Test
public void testComputeIndexSplitKeys() throws Exception {
    if (notSupported)
        return;/*w  w  w.  j  a  va  2s .c  o m*/
    String sql = " select conglomeratenumber from sys.systables t, sys.sysconglomerates c, sys.sysschemas s "
            + "where c.tableid=t.tableid and t.tablename='LINEITEM' and s.schemaid=c.schemaid and "
            + "s.schemaname='%s' and conglomeratename='L_SHIPDATE_IDX' order by 1";

    ResultSet rs = methodWatcher.executeQuery(format(sql, SCHEMA_NAME));
    rs.next();
    long conglomId = rs.getLong(1);
    methodWatcher.execute(format(
            "call SYSCS_UTIL.COMPUTE_SPLIT_KEY('%s','%s','L_SHIPDATE_IDX',"
                    + "'L_SHIPDATE,L_PARTKEY,L_EXTENDEDPRICE,L_DISCOUNT',"
                    + "'%s','|',null,null,null,null,-1,'/BAD',true,null,'%s')",
            SCHEMA_NAME, LINEITEM, getResource("shipDateIndex.csv"), getResource("data")));
    rs.close();

    String select = "SELECT \"KEY\" " + "from new com.splicemachine.derby.vti.SpliceFileVTI("
            + "'%s',NULL,'|',NULL,'HH:mm:ss','yyyy-MM-dd','yyyy-MM-dd HH:mm:ss','true','UTF-8' ) "
            + "AS splitKey (\"KEY\" varchar(200))";
    rs = methodWatcher.executeQuery(format(select, getResource("data/" + conglomId + "/keys")));
    String s = TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs);
    String expected = "KEY                                      |\n"
            + "-------------------------------------------------------------------------------\n"
            + "   \\xEC\\xC0y\\xAE\\x80\\x00\\x00\\xE2^6\\x00\\xE42'\\x93@\\x01\\x00\\xDEP\\x01\\x00\\x80    |\n"
            + "\\xEC\\xC1\\x14-H\\x00\\x00\\xE1\\x06\\xEE\\x00\\xE4V\\xA9Bp\\x01\\x00\\xDE\\xA0\\x01\\x00\\x80 |";

    Assert.assertEquals(expected, s);
}

From source file:net.solarnetwork.node.dao.jdbc.general.JdbcGeneralLocationDatumDao.java

@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public List<GeneralLocationDatum> getDatumNotUploaded(String destination) {
    return findDatumNotUploaded(new RowMapper<GeneralLocationDatum>() {

        @Override/*from ww w.j a v  a  2 s  .co m*/
        public GeneralLocationDatum mapRow(ResultSet rs, int rowNum) throws SQLException {
            if (log.isTraceEnabled()) {
                log.trace("Handling result row " + rowNum);
            }
            GeneralLocationDatum datum = new GeneralLocationDatum();
            int col = 0;
            datum.setCreated(rs.getTimestamp(++col));
            datum.setLocationId(rs.getLong(++col));
            datum.setSourceId(rs.getString(++col));

            String jdata = rs.getString(++col);
            if (jdata != null) {
                GeneralLocationDatumSamples s;
                try {
                    s = objectMapper.readValue(jdata, GeneralLocationDatumSamples.class);
                    datum.setSamples(s);
                } catch (IOException e) {
                    log.error("Error deserializing JSON into GeneralLocationDatumSamples: {}", e.getMessage());
                }
            }
            return datum;
        }
    });
}

From source file:com.saasovation.common.port.adapter.persistence.eventsourcing.mysql.MySQLJDBCEventStore.java

@SuppressWarnings("unchecked")
private List<DispatchableDomainEvent> buildEventSequence(ResultSet aResultSet) throws Exception {

    List<DispatchableDomainEvent> events = new ArrayList<DispatchableDomainEvent>();

    while (aResultSet.next()) {
        long eventId = aResultSet.getLong("event_id");

        String eventClassName = aResultSet.getString("event_type");

        String eventBody = aResultSet.getString("event_body");

        Class<DomainEvent> eventClass = (Class<DomainEvent>) Class.forName(eventClassName);

        DomainEvent domainEvent = this.serializer().deserialize(eventBody, eventClass);

        events.add(new DispatchableDomainEvent(eventId, domainEvent));
    }/*from w  ww  . j  a v  a  2s  . com*/

    return events;
}

From source file:com.flexive.core.storage.MySQL.MySQLSequencerStorage.java

/**
 * {@inheritDoc}/*from   w  ww. j  a  va  2 s  .com*/
 */
@Override
public long fetchId(String name, boolean allowRollover) throws FxCreateException {
    Connection con = null;
    PreparedStatement ps = null;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        // Prepare the new id
        ps = con.prepareStatement(SQL_NEXT);
        ps.setString(1, name);
        ps.executeUpdate();
        if (ps.getUpdateCount() == 0)
            throw new FxCreateException(LOG, "ex.sequencer.typeUnknown", name);
        ps.close();

        // Get the new id
        ps = con.prepareStatement(SQL_GETID);
        ResultSet rs = ps.executeQuery();
        long newId;
        if (rs == null || !rs.next())
            throw new FxCreateException(LOG, "ex.sequencer.fetch.failed", name);
        newId = rs.getLong(1);
        if (rs.wasNull())
            throw new FxCreateException(LOG, "ex.sequencer.fetch.failed", name);
        if (newId >= MAX_ID) {
            if (!name.startsWith("SYS_")) {
                //get allowRollover setting
                ps.close();
                ps = con.prepareStatement(SQL_GET_ROLLOVER);
                ps.setString(1, name);
                ResultSet rso = ps.executeQuery();
                if (rso == null || !rso.next())
                    throw new FxCreateException(LOG, "ex.sequencer.fetch.failed", name);
                allowRollover = rso.getBoolean(1);
            }
            if (!allowRollover)
                throw new FxCreateException("ex.sequencer.exhausted", name);
            ps.close();
            ps = con.prepareStatement(SQL_RESET);
            ps.setString(1, name);
            ps.executeUpdate();
            if (ps.getUpdateCount() == 0)
                throw new FxCreateException(LOG, "ex.sequencer.typeUnknown", name);
            newId = 0;
        }
        // Return new id
        return newId;
    } catch (SQLException exc) {
        throw new FxCreateException(LOG, exc, "ex.sequencer.fetch.failedMsg", name, exc.getMessage());
    } finally {
        Database.closeObjects(MySQLSequencerStorage.class, con, ps);
    }
}

From source file:com.linkage.community.schedule.dbutils.CustomScalarHandler.java

/**
 * Returns one <code>ResultSet</code> column as an object via the
 * <code>ResultSet.getObject()</code> method that performs type
 * conversions./*from  w w  w  .  jav a2  s. co m*/
 * @param rs <code>ResultSet</code> to process.
 * @return The column or <code>null</code> if there are no rows in
 * the <code>ResultSet</code>.
 *
 * @throws SQLException if a database access error occurs
 * @throws ClassCastException if the class datatype does not match the column type
 *
 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
 */
// We assume that the user has picked the correct type to match the column
// so getObject will return the appropriate type and the cast will succeed.

@SuppressWarnings("unchecked")
//@Override
public T handle(ResultSet rs) throws SQLException {
    Object obj = null;
    if (rs.next()) {
        if (this.columnName == null) {
            obj = rs.getObject(this.columnIndex);
            if (obj instanceof Integer)
                return (T) (obj = rs.getInt(columnIndex));
            else if (obj instanceof Long)
                return (T) (obj = (new Long(rs.getLong(columnIndex)).intValue()));
            else if (obj instanceof Boolean)
                return (T) (obj = rs.getBoolean(columnIndex));
            else if (obj instanceof Double)
                return (T) (obj = rs.getDouble(columnIndex));
            else if (obj instanceof Float)
                return (T) (obj = rs.getFloat(columnIndex));
            else if (obj instanceof Short)
                return (T) (obj = rs.getShort(columnIndex));
            else if (obj instanceof Byte)
                return (T) (obj = rs.getByte(columnIndex));
            else
                return (T) obj;
        } else {
            obj = rs.getObject(this.columnName);
            if (obj instanceof Integer)
                return (T) (obj = rs.getInt(columnName));
            else if (obj instanceof Long)
                return (T) (obj = rs.getLong(columnName));
            else if (obj instanceof Boolean)
                return (T) (obj = rs.getBoolean(columnName));
            else if (obj instanceof Double)
                return (T) (obj = rs.getDouble(columnName));
            else if (obj instanceof Float)
                return (T) (obj = rs.getFloat(columnName));
            else if (obj instanceof Short)
                return (T) (obj = rs.getShort(columnName));
            else if (obj instanceof Byte)
                return (T) (obj = rs.getByte(columnName));
            else
                return (T) obj;
        }
    }
    return null;
}

From source file:org.jrecruiter.service.migration.impl.MigrationServiceImpl.java

@Override
@Transactional//ww  w .  j  a va  2  s.  c om
public void migrateJobData() {

    jobService.updateJobCountPerDays();

    LOGGER.info("Migrating jobs...");

    userDao.getAll();

    String sql = "SELECT job_id, business_name, business_location, job_title, salary, "
            + "description, web_site, business_address1, business_address2, "
            + "business_city, business_state, business_zip, business_phone, "
            + "business_email, industry, job_restrictions, register_date, expire_date, "
            + "update_date, status, user_name " + "FROM jobs order by register_date asc;";

    ParameterizedRowMapper<Job> mapper = new ParameterizedRowMapper<Job>() {

        // notice the return type with respect to Java 5 covariant return types
        public Job mapRow(ResultSet rs, int rowNum) throws SQLException {
            Job job = new Job();

            job.setId(rs.getLong("job_id"));
            job.setBusinessName(rs.getString("business_name"));
            job.setBusinessCity(rs.getString("business_location"));

            job.setJobTitle(rs.getString("job_title"));
            job.setSalary(rs.getString("salary"));

            job.setDescription(rs.getString("description"));
            job.setWebsite(rs.getString("web_site"));
            job.setBusinessAddress1(rs.getString("business_address1"));
            job.setBusinessAddress2(rs.getString("business_address2"));

            job.setBusinessCity(rs.getString("business_city"));
            job.setBusinessState(rs.getString("business_state"));
            job.setBusinessZip(rs.getString("business_zip"));
            job.setBusinessPhone(rs.getString("business_phone"));
            job.setBusinessEmail(rs.getString("business_email"));
            job.setIndustryOther(rs.getString("industry"));
            job.setJobRestrictions(rs.getString("job_restrictions"));
            job.setRegistrationDate(rs.getDate("register_date"));
            job.setUpdateDate(rs.getDate("update_date"));
            job.setStatus(JobStatus.ACTIVE);
            job.setUsesMap(Boolean.FALSE);

            //Let's populated the universal id

            job.setUniversalId(rs.getString("job_id"));

            final User user = userDao.getUser(rs.getString("user_name"));
            LOGGER.info("Fetching user: " + rs.getString("user_name") + ".");
            if (user == null) {
                throw new IllegalStateException("No user found for user name: " + rs.getString("user_name"));
            }

            job.setUser(user);

            return job;
        }
    };

    final List<Job> jobs = this.jdbcTemplateV1.query(sql, mapper);

    //Populating statistics

    int counterForStatistics = 0;
    for (Job job : jobs) {
        Statistic statistic = this.getStatistic(job.getId());
        LOGGER.info("[" + ++counterForStatistics + "/" + jobs.size() + "] Old  Id: " + job.getId()
                + "...assigning statistics: " + statistic);
        if (statistic == null) {
            throw new IllegalStateException("Statistic should not be null.");
        }
        statistic.setJob(job);
        job.setStatistic(statistic);
    }

    int counter = 0;

    Industry otherIndustry = industryDao.get(CommongKeyIds.OTHER.getId());

    Region otherRegion = regionDao.get(CommongKeyIds.OTHER.getId());

    for (Job job : jobs) {
        LOGGER.info("[" + ++counter + "/" + jobs.size() + "] Job: " + job + ".");

        final Job newJob = new Job();
        newJob.setBusinessAddress1(job.getBusinessAddress1());
        newJob.setBusinessAddress2(job.getBusinessAddress2());
        newJob.setBusinessCity(job.getBusinessCity());
        newJob.setBusinessEmail(job.getBusinessEmail());
        newJob.setBusinessName(job.getBusinessName());
        newJob.setBusinessPhone(job.getBusinessPhone());
        newJob.setBusinessState(job.getBusinessState());
        newJob.setBusinessZip(job.getBusinessZip());
        newJob.setDescription(job.getDescription());
        newJob.setIndustry(otherIndustry);
        newJob.setRegion(otherRegion);
        newJob.setIndustryOther(job.getIndustryOther());
        newJob.setJobRestrictions(job.getJobRestrictions());
        newJob.setJobTitle(job.getJobTitle());
        newJob.setSalary(job.getSalary());
        newJob.setUniversalId(job.getUniversalId());

        newJob.setStatus(JobStatus.ACTIVE);

        if (job.getRegistrationDate() != null) {
            newJob.setRegistrationDate(job.getRegistrationDate());
        } else if (job.getUpdateDate() != null) {
            newJob.setRegistrationDate(job.getUpdateDate());
        } else {
            throw new IllegalStateException("Both Registration Date and Update Date are null for Job: " + job);
        }

        newJob.setUpdateDate(job.getUpdateDate());
        newJob.setUser(job.getUser());
        newJob.setUsesMap(Boolean.FALSE);
        newJob.setWebsite(job.getWebsite());

        Statistic newStatistic = new Statistic();
        newStatistic.setJob(newJob);
        newStatistic.setCounter(job.getStatistic().getCounter());
        newStatistic.setLastAccess(job.getStatistic().getLastAccess());

        newJob.setStatistic(newStatistic);

        jobService.addJob(newJob);

    }

    entityManager.flush();
    LOGGER.info("Total number of jobs migrated: " + jobs.size());

}

From source file:com.hadoopilluminated.examples.DBCountPageView.java

/**
 * Verifies the results are correct/*  www  .  j  a  v a  2  s . c o m*/
 */
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;
    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:com.github.gaoyangthu.demo.mapred.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;/*  w ww  .  j  av  a2  s  .co 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();
    }
}