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.hs.mail.imap.dao.MySqlMessageDao.java

public PhysMessage getDanglingMessageID(long messageID) {
    String sql = "SELECT m.physmessageid, p.internaldate FROM message m, physmessage p WHERE m.physmessageid = (SELECT physmessageid FROM message WHERE messageid = ?) AND p.id=m.physmessageid GROUP BY m.physmessageid HAVING COUNT(m.physmessageid) = 1";
    return (PhysMessage) queryForObject(sql, new Object[] { new Long(messageID) }, new RowMapper() {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            PhysMessage pm = new PhysMessage();
            pm.setPhysMessageID(rs.getLong("physmessageid"));
            pm.setInternalDate(new Date(rs.getTimestamp("internaldate").getTime()));
            return pm;
        }/*from   w w w . ja  v  a 2s  .c  om*/
    });
}

From source file:de.ingrid.importer.udk.strategy.v2.IDCStrategy2_3_0_checkInspireObjects.java

protected void checkInspireObjectsConformity() throws Exception {
    if (log.isInfoEnabled()) {
        log.info(//from ww w. j  a v  a2  s. c o  m
                "Check objects with INSPIRE themes for INSPIRE compatibility (-> PROTOCOL of objects with missing data)...");
    }

    String sql = "select " + "oNode.id as oNodeId, oNode.obj_uuid, oNode.obj_id, oNode.obj_id_published, " + // object node
            "obj.obj_name, " + // object
            "objSearchTermValue.entry_id as inspireKey, " + // INSPIRE theme
            "objGeo.referencesystem_key, " + // Raumbezugssystem: mandatory
            "objFormat.format_key, objFormat.format_value, objFormat.ver as formatVersion, " + // Datenformat: Name + Version: mandatory
            "objAdr.type as adrRefKey, objAdr.special_ref as adrRefListId, objAdr.adr_uuid " + // Adressen: "Auskunft" + "Datenverantwortung" : mandatory
            "from " + "object_node oNode " +
            // always join "working version" ! equals published version, if no working version
            "join t01_object obj on (oNode.obj_id = obj.id) "
            + "join searchterm_obj objSearchTerm on (obj.id = objSearchTerm.obj_id) "
            + "join searchterm_value objSearchTermValue on (objSearchTerm.searchterm_id = objSearchTermValue.id) "
            + "left join t011_obj_geo objGeo on (obj.id = objGeo.obj_id) "
            + "left join t0110_avail_format objFormat on (obj.id = objFormat.obj_id) "
            + "left join t012_obj_adr objAdr on (obj.id = objAdr.obj_id) " + "where "
            + "objSearchTermValue.type = 'I' " + "and objSearchTermValue.entry_id != 99999 " + // "Kein INSPIRE Thema"
            "order by obj_id";

    HelperStatistics stats = new HelperStatistics();
    HelperObject currentObj = null;

    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery(sql, st);
    while (rs.next()) {
        long nextObjId = rs.getLong("obj_id");

        // check whether all data of an object is read, then process object !
        boolean objChange = false;
        if (currentObj != null && currentObj.objId != nextObjId) {
            // object changed, process finished object
            objChange = true;
            processObject(currentObj, stats);
        }

        if (currentObj == null || objChange) {
            // set up next object
            currentObj = new HelperObject(rs.getLong("oNodeId"), rs.getString("obj_uuid"), nextObjId,
                    rs.getLong("obj_id_published"), rs.getString("obj_name"));
        }

        // pass read stuff to object
        currentObj.addInspireTheme(rs.getInt("inspireKey"));
        currentObj.addReferencesystem(rs.getInt("referencesystem_key"));
        currentObj.addDataFormat(rs.getInt("format_key"), rs.getString("format_value"),
                rs.getString("formatVersion"));
        currentObj.addAddress(rs.getInt("adrRefKey"), rs.getInt("adrRefListId"), rs.getString("adr_uuid"));
    }
    // also process last object ! not done in loop due to end of loop !
    if (currentObj != null) {
        processObject(currentObj, stats);
    }

    rs.close();
    st.close();

    // Protocol also to System.out !

    String msg = "\nChecked " + stats.numInspire + " INSPIRE objects on missing data.";
    System.out.println("\n" + msg + " See also log file.");
    log.info(msg);

    if (stats.objsMissingData.size() > 0) {
        msg = "The following " + stats.objsMissingData.size()
                + " objects are not INSPIRE conform due to missing data. Please edit manually and publish again !\n\n"
                + stats.getObjMissingDataAsString();
        System.out.println("\n" + msg + "See also log file (WARN).");
        log.warn(msg);
    } else {
        msg = "No INSPIRE objects with missing data found !";
        System.out.println("\n" + msg);
        log.info(msg);
    }

    if (log.isInfoEnabled()) {
        log.info(
                "Check objects with INSPIRE themes for INSPIRE compatibility (-> PROTOCOL of objects with missing data)... done");
    }
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGMutatiesDAO.java

@Override
public List<BAGMutatie> getNextBAGMutaties() {
    try {//from w  w w.  j a va 2  s  .c o  m
        List<BAGMutatie> result = jdbcTemplate
                .query("select id, tijdstip_verwerking, volgnr_verwerking, object_type, mutatie_product"
                        + " from bag_mutatie"
                        + " where tijdstip_verwerking = (select min(tijdstip_verwerking) from bag_mutatie)"
                        + " order by volgnr_verwerking asc", new RowMapper<BAGMutatie>() {
                            @Override
                            public BAGMutatie mapRow(ResultSet rs, int row) throws SQLException {
                                try {
                                    BAGMutatie result = new BAGMutatie();
                                    result.setId(rs.getLong("id"));
                                    result.setTijdstipVerwerking(Utils
                                            .toXMLGregorianCalendar(rs.getTimestamp("tijdstip_verwerking")));
                                    result.setVolgnrVerwerking(rs.getInt("volgnr_verwerking"));
                                    result.setObjectType(BAGObjectType.values()[rs.getInt("object_type")]);
                                    result.setMutatieProduct(XMLMessageBuilder.getInstance(MutatieProduct.class)
                                            .handle(rs.getCharacterStream("mutatie_product"),
                                                    MutatieProduct.class));
                                    return result;
                                } catch (JAXBException e) {
                                    throw new DAOException(e);
                                }
                            }
                        });
        return result;
    } catch (DataAccessException e) {
        throw new DAOException(e);
    }
}

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

@Override
public LogRegion getHighWaterMark(String collection) throws IOException {
    try (Connection conn = dataSource.getConnection();
            PreparedStatement stmt = conn.prepareStatement(HIGH_WATERMARK_SQL)) {
        stmt.setString(1, collection);/*  www  .  j a  va2  s.  c  o m*/
        ResultSet rset = stmt.executeQuery();

        if (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"));
            return logRegion;
        }
    } catch (SQLException e) {
        LOG.error("SQL error getting high watermark for {}", collection, e);
    }

    return null;
}

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

/**
 * {@inheritDoc}//from   ww  w .ja  va 2 s  .c  o  m
 */
@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, H2_SEQ_PREFIX + name);
        ps.setString(2, H2_SEQ_PREFIX + name);
        ResultSet rs = ps.executeQuery();
        long curr, newId;
        if (rs != null && rs.next()) {
            curr = rs.getLong(1);
            newId = rs.getLong(2);
        } else
            throw new FxCreateException(LOG, "ex.sequencer.fetch.failed", name);
        if (curr == newId || curr < -1 || newId >= getMaxId() || newId < curr) {
            if (!name.startsWith("SYS_")) {
                //get allowRollover setting
                ps.close();
                ps = con.prepareStatement(SQL_GET_COMMENT + "?");
                ps.setString(1, H2_SEQ_PREFIX + name);
                ResultSet rso = ps.executeQuery();
                if (rso == null || !rso.next())
                    throw new FxCreateException(LOG, "ex.sequencer.fetch.failed", name);
                allowRollover = ROLLOVER.equals(rso.getString(1));
            }
            if (!allowRollover)
                throw new FxCreateException("ex.sequencer.exhausted", name);
            //reset it
            ps.close();
            ps = con.prepareStatement("ALTER SEQUENCE " + H2_SEQ_PREFIX + name + " RESTART WITH 1");
            ps.executeUpdate();
            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(H2SequencerStorage.class, con, ps);
    }
}

From source file:com.l2jfree.gameserver.instancemanager.InstanceManager.java

public void restoreInstanceTimes(int playerObjId) {
    if (_playerInstanceTimes.containsKey(playerObjId))
        return; // already restored
    _playerInstanceTimes.put(playerObjId, new FastMap<Integer, Long>());
    Connection con = null;//from   w w w.j  a  v a 2s  .c o  m
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement = con.prepareStatement(RESTORE_INSTANCE_TIMES);
        statement.setInt(1, playerObjId);
        ResultSet rset = statement.executeQuery();

        while (rset.next()) {
            int id = rset.getInt("instanceId");
            long time = rset.getLong("time");
            if (time < System.currentTimeMillis())
                deleteInstanceTime(playerObjId, id);
            else
                _playerInstanceTimes.get(playerObjId).put(id, time);
        }

        rset.close();
        statement.close();
    } catch (Exception e) {
        _log.warn("Could not delete character instance time data: ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:de.iritgo.aktario.buddylist.BuddyListManager.java

public void generateGroups(final User user) {
    final DataSource dataSource = (DataSource) CommandTools.performSimple("persist.GetDefaultDataSource");
    final BuddyList buddyList = addBuddyList(user);
    final ResourceService resources = Engine.instance().getResourceService();

    QueryRunner query = new QueryRunner(dataSource);
    try {//ww  w. j  ava 2s .c  om
        query.query(
                "select * from akteragroup left join akteragroupentry on akteragroup.id = akteragroupentry.groupid left join keelusers on keelusers.uniqid = akteragroupentry.userid where keelusers.username="
                        + "'" + user.getName() + "' and akteragroup.visible = true",
                new ResultSetHandler() {
                    public Object handle(ResultSet rs) throws SQLException {
                        while (rs.next()) {
                            try {
                                long groupId = rs.getLong("groupId");

                                String displayName = rs.getString("title");
                                if (StringTools.isTrimEmpty(displayName)) {
                                    displayName = rs.getString("name");
                                }
                                displayName = resources.getStringWithoutException(displayName);
                                final BuddyListGroup buddyListGroup = addBuddyListGroup(user, buddyList,
                                        groupId, displayName);

                                QueryRunner query2 = new QueryRunner(dataSource);

                                query2.query(
                                        "select * from akteragroup left join akteragroupentry on akteragroup.id = akteragroupentry.groupid "
                                                + "left join keelusers on keelusers.uniqid = akteragroupentry.userid where akteragroup.id="
                                                + groupId,
                                        new ResultSetHandler() {
                                            public Object handle(ResultSet rs) throws SQLException {
                                                while (rs.next()) {
                                                    try {
                                                        addParticipant(rs.getString("username"),
                                                                buddyListGroup);
                                                    } catch (Exception ignored) {
                                                        Log.logError("persist", "LoadObject",
                                                                "NoSuchIObjectException");
                                                        ignored.printStackTrace();
                                                    }
                                                }

                                                return null;
                                            }
                                        });
                            } catch (Exception x) {
                                Log.logError("plugin", "BuddyListManager.generateGroups", x.toString());
                            }
                        }

                        return null;
                    }
                });
    } catch (Exception x) {
        Log.logError("plugin", "BuddyListManager.generateGroups", x.toString());
    }
}

From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldDBDAO.java

/**
 * Read an ExtendedField from database./*from  www.java2  s.c om*/
 * @param connection A connection to the harvestDatabase
 * @param aExtendedfieldId The ID for a given ExtendedField 
 * @return An ExtendedField object for the given ID.
 */
private synchronized ExtendedField read(Connection connection, Long aExtendedfieldId) {
    if (!exists(connection, aExtendedfieldId)) {
        throw new UnknownID("Extended Field id " + aExtendedfieldId + " is not known in persistent storage");
    }

    ExtendedField extendedField = null;
    PreparedStatement statement = null;
    try {
        statement = connection.prepareStatement("" + "SELECT extendedfieldtype_id, " + "       name, "
                + "       format, " + "       defaultvalue, " + "       options, " + "       datatype, "
                + "       mandatory, " + "       sequencenr, " + "       maxlen " + "FROM   extendedfield "
                + "WHERE  extendedfield_id = ? ");

        statement.setLong(1, aExtendedfieldId);
        ResultSet result = statement.executeQuery();
        result.next();

        long extendedfieldtypeId = result.getLong(1);
        String name = result.getString(2);
        String format = result.getString(3);
        String defaultvalue = result.getString(4);
        String options = result.getString(5);
        int datatype = result.getInt(6);
        //TODO maybe this cast is not necessary
        boolean mandatory = (result.getInt(7) != 0);
        int sequencenr = result.getInt(8);
        int maxlen = result.getInt(9);

        extendedField = new ExtendedField(aExtendedfieldId, extendedfieldtypeId, name, format, datatype,
                mandatory, sequencenr, defaultvalue, options, maxlen);

        return extendedField;
    } catch (SQLException e) {
        String message = "SQL error reading extended Field " + aExtendedfieldId + " in database" + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new IOFailure(message, e);
    }
}

From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO.java

/**
 * Read the ExtendedFieldValue with the given extendedFieldID.
 * @param connection an open connection to the HarvestDatabase
 * @param aExtendedFieldID A given ID for a ExtendedFieldValue
 * @param aInstanceID A given instanceID
 * @return the ExtendedFieldValue with the given extendedFieldID.
 *///w ww  . j  av a 2  s .c  om
private synchronized ExtendedFieldValue read(Connection connection, Long aExtendedFieldID, Long aInstanceID) {
    ExtendedFieldValue extendedFieldValue = null;
    PreparedStatement statement = null;
    try {
        statement = connection.prepareStatement(
                "" + "SELECT extendedfieldvalue_id, " + "       extendedfield_id, " + "       content "
                        + "FROM extendedfieldvalue " + "WHERE  extendedfield_id = ? and instance_id = ?");

        statement.setLong(1, aExtendedFieldID);
        statement.setLong(2, aInstanceID);
        ResultSet result = statement.executeQuery();
        if (!result.next()) {
            return null;
        }

        long extendedfieldvalueId = result.getLong(1);
        long extendedfieldId = result.getLong(2);
        long instanceId = aInstanceID;
        String content = result.getString(3);

        extendedFieldValue = new ExtendedFieldValue(extendedfieldvalueId, extendedfieldId, instanceId, content);

        return extendedFieldValue;
    } catch (SQLException e) {
        String message = "SQL error reading extended Field " + aExtendedFieldID + " in database" + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new IOFailure(message, e);
    }
}

From source file:iddb.runtime.db.model.dao.impl.mysql.UserDAOImpl.java

@Override
public void save(User user) {
    String sql;//from ww w. j  a v a  2 s.  co m
    if (user.getKey() == null) {
        sql = "insert into user (loginid, roles, updated, created, password) values (?,?,?,?,?)";
    } else {
        sql = "update user set loginid = ?," + "roles = ?," + "updated = ? where id = ? limit 1";
    }
    Connection conn = null;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        st.setString(1, user.getLoginId());
        st.setString(2, Functions.join(user.getRoles(), ","));
        st.setTimestamp(3, new Timestamp(new Date().getTime()));
        if (user.getKey() != null) {
            st.setLong(4, user.getKey());
        } else {
            st.setTimestamp(4, new Timestamp(new Date().getTime()));
            st.setString(5, user.getPassword());
        }
        st.executeUpdate();
        if (user.getKey() == null) {
            ResultSet rs = st.getGeneratedKeys();
            if (rs != null && rs.next()) {
                user.setKey(rs.getLong(1));
            } else {
                logger.warn("Couldn't get id for user {}", user.getLoginId());
            }
        }
    } catch (SQLException e) {
        logger.error("Save: {}", e);
    } catch (IOException e) {
        logger.error("Save: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}