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.ccoe.build.dal.ProjectMapper.java

public Project mapRow(ResultSet rs, int arg1) throws SQLException {
    Project project = new Project();
    project.setName(rs.getString("name"));
    project.setGroupId(rs.getString("group_id"));
    project.setArtifactId(rs.getString("artifact_id"));
    project.setType(rs.getString("type"));
    project.setVersion(rs.getString("version"));
    project.setStartTime(rs.getDate("start_time"));
    project.setDuration(rs.getLong("duration"));
    project.setStatus(rs.getString("status"));
    return project;
}

From source file:fi.okm.mpass.shibboleth.profile.impl.StoreMonitoringResultTest.java

protected void assertResult(final Connection connection, final ResultSet set, final int id,
        final long startTime, final long endTime) throws Exception {
    Assert.assertTrue(set.next());//from   w  ww .java2s.  c om
    Assert.assertEquals(id, set.getBigDecimal(1).longValue());
    Assert.assertEquals(startTime, set.getLong("startTime"));
    Assert.assertEquals(endTime, set.getLong("endTime"));
    Assert.assertEquals(sequenceId, set.getString("sourceId"));
    final PreparedStatement getStepResults = connection.prepareStatement("SELECT * from "
            + StoreMonitoringResult.TABLE_NAME_MONITORING_STEP_RESULTS + " where resultId=" + id);
    final ResultSet stepSet = getStepResults.executeQuery();
    Assert.assertTrue(stepSet.next());
    Assert.assertEquals(startTime, stepSet.getLong("startTime"));
    Assert.assertEquals(endTime, stepSet.getLong("endTime"));
    Assert.assertFalse(stepSet.next());
}

From source file:com.sf.ddao.ops.InsertAndGetGeneratedKeySqlOperation.java

public boolean execute(Context context) throws Exception {
    try {//from  www  .  jav  a2 s .  c  o  m
        final MethodCallCtx callCtx = CtxHelper.get(context, MethodCallCtx.class);
        PreparedStatement preparedStatement = statementFactory.createStatement(context, true);
        Object res = null;
        preparedStatement.executeUpdate();
        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        if (resultSet.next()) {
            if (method.getReturnType() == Integer.TYPE || method.getReturnType() == Integer.class) {
                res = resultSet.getInt(1);
            } else if (method.getReturnType() == Long.TYPE || method.getReturnType() == Long.class) {
                res = resultSet.getLong(1);
            } else if (method.getReturnType() == BigDecimal.class) {
                res = resultSet.getBigDecimal(1);
            }
        }
        resultSet.close();
        preparedStatement.close();
        callCtx.setLastReturn(res);
        return CONTINUE_PROCESSING;
    } catch (Exception t) {
        throw new DaoException("Failed to execute sql operation for " + method, t);
    }
}

From source file:com.github.brandtg.switchboard.JdbcBasedLogIndex.java

@Override
public List<LogRegion> getLogRegions(String collection, long startIndex, int count, boolean includeStart)
        throws IOException {
    List<LogRegion> logRegions = new ArrayList<LogRegion>();

    String sql;//from  w  w  w . j av  a 2s .  c  om
    if (includeStart) {
        sql = String.format(SELECT_SQL, ">=");
    } else {
        sql = String.format(SELECT_SQL, ">");
    }

    try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) {
        stmt.setString(1, collection);
        stmt.setLong(2, startIndex);
        stmt.setInt(3, count);
        ResultSet rset = stmt.executeQuery();

        while (rset.next()) {
            LogRegion logRegion = new LogRegion();
            logRegion.setIndex(rset.getLong("index"));
            logRegion.setFileName(rset.getString("file_name"));
            logRegion.setFileOffset(rset.getLong("file_offset"));
            logRegion.setNextFileOffset(rset.getLong("next_file_offset"));
            logRegions.add(logRegion);
        }
    } catch (SQLException e) {
        LOG.error("SQL error reading {}", collection, e);
    }

    return logRegions;
}

From source file:be.fgov.kszbcss.rhq.websphere.component.jdbc.db2.SnapshotMeasurementGroupHandler.java

public void getValues(WebSphereServer server, MeasurementReport report,
        Map<String, MeasurementScheduleRequest> requests) {
    try {/*from   w w  w  .  j a  va 2  s. co m*/
        DB2MonitorContext context = monitor.getContext();
        Map<String, Object> dataSourceProps = context.getDataSourceProperties();

        // TODO: this should be done in ConnectionContext!
        String clientProgramName = (String) dataSourceProps.get("clientProgramName");
        if (clientProgramName == null || clientProgramName.length() == 0) {
            log.warn("clientProgramName not configured for data source "
                    + monitor.getParent().getResourceContext().getResourceKey()
                    + "; unable to correlate snapshot data");
            return;
        }
        final String applName = adminOperations.expandVariable(clientProgramName);
        if (log.isDebugEnabled()) {
            log.debug("clientProgramName = " + applName);
        }

        final Set<String> baseMetrics = new LinkedHashSet<String>();
        for (String name : requests.keySet()) {
            int idx = name.indexOf(':');
            if (idx == -1) {
                baseMetrics.add(name);
            } else {
                baseMetrics.add(name.substring(0, idx));
                baseMetrics.add(name.substring(idx + 1));
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("The following base metrics will be requested from DB2: " + baseMetrics);
        }

        StringBuilder buffer = new StringBuilder("SELECT A.AGENT_ID");
        for (String name : baseMetrics) {
            buffer.append(", ");
            String expression = expressions.get(name);
            buffer.append(expression == null ? name : expression);
        }
        buffer.append(
                " FROM SYSIBMADM.SNAPAPPL AS A, SYSIBMADM.SNAPAPPL_INFO AS AI WHERE A.AGENT_ID=AI.AGENT_ID AND AI.APPL_NAME=?");
        final String sql = buffer.toString();

        if (log.isDebugEnabled()) {
            log.debug("Preparing to execute statement: " + sql);
        }

        final DB2BaseMetricData[] newData = new DB2BaseMetricData[baseMetrics.size()];
        for (int i = 0; i < newData.length; i++) {
            newData[i] = new DB2BaseMetricData();
        }
        context.execute(new Query<Void>() {
            public Void execute(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(sql);
                try {
                    stmt.setString(1, applName);
                    ResultSet rs = stmt.executeQuery();
                    try {
                        while (rs.next()) {
                            long agentId = rs.getLong(1);
                            for (int i = 0; i < baseMetrics.size(); i++) {
                                newData[i].addValue(agentId, rs.getLong(i + 2));
                            }
                        }
                    } finally {
                        rs.close();
                    }
                } finally {
                    stmt.close();
                }
                return null;
            }
        });

        int i = 0;
        for (String name : baseMetrics) {
            DB2BaseMetricData raw = newData[i++];
            if (dynamicBaseMetrics.contains(name)) {
                baseMetricData.put(name, raw);
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Processing data for dynamic base metric " + name + "; raw value: " + raw.getSum());
                }
            } else {
                DB2BaseMetricData adjusted = baseMetricData.get(name);
                if (adjusted == null) {
                    baseMetricData.put(name, raw);
                    adjusted = raw;
                } else {
                    adjusted.update(raw);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Processing data for counter " + name + "; raw value: " + raw.getSum()
                            + "; adjusted value: " + adjusted.getSum());
                }
            }
        }

        for (Map.Entry<String, MeasurementScheduleRequest> request : requests.entrySet()) {
            String name = request.getKey();
            int idx = name.indexOf(':');
            if (idx == -1) {
                report.addData(new MeasurementDataNumeric(request.getValue(),
                        (double) baseMetricData.get(name).getSum()));
            } else {
                DB2AverageMetricData current = new DB2AverageMetricData(
                        baseMetricData.get(name.substring(0, idx)).getSum(),
                        baseMetricData.get(name.substring(idx + 1)).getSum());
                DB2AverageMetricData previous = averageMetricData.put(name, current);
                if (previous != null) {
                    long countDelta = current.getCount() - previous.getCount();
                    if (countDelta > 0) {
                        report.addData(new MeasurementDataNumeric(request.getValue(),
                                ((double) (current.getTotal() - previous.getTotal())) / ((double) countDelta)));
                    }
                }
            }
        }
    } catch (Exception ex) {
        log.error("Failed to collect metrics", ex);
    }
}

From source file:com.flexive.core.storage.H2.H2SequencerStorage.java

/**
 * {@inheritDoc}// www .ja v  a2s. co  m
 */
@Override
public List<CustomSequencer> getCustomSequencers() throws FxApplicationException {
    List<CustomSequencer> res = new ArrayList<CustomSequencer>(20);
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement(SQL_GET_USER);
        ResultSet rs = ps.executeQuery();
        while (rs != null && rs.next())
            res.add(new CustomSequencer(rs.getString(1), ROLLOVER.equals(rs.getString(2)), rs.getLong(3)));
    } catch (SQLException exc) {
        throw new FxDbException(LOG, exc, "ex.db.sqlError", exc.getMessage());
    } finally {
        Database.closeObjects(H2SequencerStorage.class, con, ps);
    }
    return res;
}

From source file:de.tu_berlin.dima.oligos.db.HistogramHandler.java

@Override
public Map<T, Long> handle(ResultSet rs) throws SQLException {
    Map<T, Long> mostFrequentValues = Maps.newLinkedHashMap();
    while (rs.next()) {
        String colvalue = (keyColumnName != null) ? rs.getString(keyColumnName) : rs.getString(keyColumnIndex);
        if (colvalue != null) {
            T value = parser.fromString(colvalue.replaceAll("'", ""));
            long count = (valColumnName != null) ? rs.getLong(valColumnName) : rs.getLong(valColumnIndex);
            mostFrequentValues.put(value, count);
        }/*from ww  w  . j  ava  2 s. c  o m*/
    }
    return mostFrequentValues;
}

From source file:net.mindengine.oculus.frontend.service.project.JdbcProjectDAO.java

@Override
public Long createProject(Project project) throws Exception {

    PreparedStatement ps = getConnection().prepareStatement(
            "insert into projects (name, description, path, parent_id, icon, author_id, date) values (?,?,?,?,?,?,?)",
            Statement.RETURN_GENERATED_KEYS);

    ps.setString(1, project.getName());/*ww  w.  jav a2s .com*/
    ps.setString(2, project.getDescription());
    ps.setString(3, project.getPath());
    ps.setLong(4, project.getParentId());
    ps.setString(5, project.getIcon());
    ps.setLong(6, project.getAuthorId());
    ps.setTimestamp(7, new Timestamp(project.getDate().getTime()));

    ps.executeUpdate();
    ResultSet rs = ps.getGeneratedKeys();
    Long projectId = null;
    if (rs.next()) {
        projectId = rs.getLong(1);
    }

    if (project.getParentId() > 0) {
        // Increasing the parents project subprojects_count var
        update("update projects set subprojects_count = subprojects_count+1 where id = :id", "id",
                project.getParentId());
    }

    return projectId;
}

From source file:com.linuxbox.enkive.audit.sqldb.SqlDbAuditService.java

@Override
public long getAuditEntryCount() throws AuditServiceException {
    AuditOperation<Long> op = new AuditOperation<Long>() {
        @Override/*from  ww w  .  j a  v  a 2  s. c om*/
        public Long execute(Connection connection) throws SQLException, AuditServiceException {
            long count = 0;

            PreparedStatement statement = connection.prepareStatement(COUNT_STATEMENT);
            setStatement(statement);

            ResultSet resultSet = statement.executeQuery();
            setResultSet(resultSet);
            if (resultSet.next()) {
                count = resultSet.getLong(1);
            } else {
                throw new AuditServiceException("could not count the number of entries in the audit log");
            }

            return count;
        }
    };

    return op.executeAuditOperation();
}

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

private Statistic getStatistic(Long oldJobId) {

    final String sql = "select counter, last_access, unique_visits "
            + "from statistics where statistics.job_id = ?";

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

        public Statistic mapRow(ResultSet rs, int rowNum) throws SQLException {
            Statistic statistic = new Statistic();
            statistic.setCounter(rs.getLong("unique_visits"));
            statistic.setLastAccess(rs.getTimestamp("last_access"));

            return statistic;
        }//from  ww w . jav  a  2 s.c  om
    };

    return this.jdbcTemplateV1.queryForObject(sql, mapper, oldJobId);

}