Example usage for java.sql ResultSet getTimestamp

List of usage examples for java.sql ResultSet getTimestamp

Introduction

In this page you can find the example usage for java.sql ResultSet getTimestamp.

Prototype

java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Timestamp object in the Java programming language.

Usage

From source file:dk.netarkivet.harvester.datamodel.DomainDBDAO.java

/**
 * Read owner info entries for the domain.
 * @param c //from   ww w .jav  a  2s. c om
 *            A connection to the database
 * @param d
 *            The domain being read. Its ID must be set.
 * @throws SQLException
 *             If database errors occur.
 */
private void readOwnerInfo(Connection c, Domain d) throws SQLException {
    // Read owner info
    PreparedStatement s = c
            .prepareStatement("SELECT ownerinfo_id, created, info" + " FROM ownerinfo WHERE domain_id = ?");
    s.setLong(1, d.getID());
    ResultSet res = s.executeQuery();
    while (res.next()) {
        final DomainOwnerInfo ownerinfo = new DomainOwnerInfo(new Date(res.getTimestamp(2).getTime()),
                res.getString(3));
        ownerinfo.setID(res.getLong(1));
        d.addOwnerInfo(ownerinfo);
    }
}

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

@Test
public void testImportNullFields() throws Exception {
    PreparedStatement ps = methodWatcher.prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA(" + "'%s'," + // schema name
            "'%s'," + // table name
            "null," + // insert column list
            "'%s'," + // file path
            "','," + // column delimiter
            "'%s'," + // character delimiter
            "null," + // timestamp format
            "null," + // date format
            "null," + // time format
            "%d," + // max bad records
            "'%s'," + // bad record dir
            "null," + // has one line records
            "null)", // char set
            spliceSchemaWatcher.schemaName, TABLE_10, getResourceDirectory() + "null_field.csv", "\"", 0,
            BADDIR.getCanonicalPath()));
    ps.execute();/*  w  ww.  j av a 2 s  .c o m*/

    ResultSet rs = methodWatcher
            .executeQuery(format("select * from %s.%s", spliceSchemaWatcher.schemaName, TABLE_10));
    int count = 0;
    while (rs.next()) {
        Integer i = rs.getInt(1);
        Float j = rs.getFloat(2);
        String k = rs.getString(3);
        Timestamp l = rs.getTimestamp(4);
        Assert.assertEquals(i.byteValue(), 0);
        Assert.assertEquals(j.byteValue(), 0);
        Assert.assertNull("String failure " + k, k);
        Assert.assertNull("Timestamp failure " + l, l);
        count++;
    }
    Assert.assertTrue("import failed!" + count, count == 1);
}

From source file:database.DataLoader.java

private Date getTimestampOrToday(ResultSet set, String paramName) {
    try {/*from  ww w  .j a va2 s. c om*/
        return new Date(set.getTimestamp(paramName).getTime());
    } catch (Exception e) {
        return new Date();
    }
}

From source file:dk.netarkivet.harvester.datamodel.HarvestDefinitionDBDAO.java

/**
 * Get all sparse versions of partial harvests for GUI purposes ordered by
 * name.//  w  w w .j  a  v  a  2 s  .  c  om
 *
 * @return An iterable (possibly empty) of SparsePartialHarvests
 */
public Iterable<SparsePartialHarvest> getSparsePartialHarvestDefinitions(boolean excludeInactive) {
    Connection c = HarvestDBConnection.get();
    PreparedStatement s = null;
    String query = "SELECT harvestdefinitions.harvest_id," + "       harvestdefinitions.name,"
            + "       harvestdefinitions.comments," + "       harvestdefinitions.numevents,"
            + "       harvestdefinitions.submitted," + "       harvestdefinitions.isactive,"
            + "       harvestdefinitions.edition," + "       schedules.name,"
            + "       partialharvests.nextdate, " + "       harvestdefinitions.audience, "
            + "       harvestdefinitions.channel_id " + "FROM harvestdefinitions, partialharvests, schedules"
            + " WHERE harvestdefinitions.harvest_id " + "       = partialharvests.harvest_id"
            + " AND (harvestdefinitions.isactive " + " = ?"
            // This linie is duplicated to allow to select both active
            // and inactive HD's.
            + " OR harvestdefinitions" + ".isactive " + " = ?)" + "   AND schedules.schedule_id "
            + "       = partialharvests.schedule_id " + "ORDER BY harvestdefinitions.name";
    try {
        s = DBUtils.prepareStatement(c, query, true, excludeInactive);
        ResultSet res = s.executeQuery();
        List<SparsePartialHarvest> harvests = new ArrayList<SparsePartialHarvest>();
        while (res.next()) {
            SparsePartialHarvest sph = new SparsePartialHarvest(res.getLong(1), res.getString(2),
                    res.getString(3), res.getInt(4), new Date(res.getTimestamp(5).getTime()), res.getBoolean(6),
                    res.getLong(7), res.getString(8), DBUtils.getDateMaybeNull(res, 9), res.getString(10),
                    DBUtils.getLongMaybeNull(res, 11));
            harvests.add(sph);
        }
        return harvests;
    } catch (SQLException e) {
        throw new IOFailure("SQL error getting sparse harvests" + "\n" + ExceptionUtils.getSQLExceptionCause(e),
                e);
    } finally {
        DBUtils.closeStatementIfOpen(s);
        HarvestDBConnection.release(c);
    }
}

From source file:com.adanac.module.blog.dao.ArticleDao.java

public Map<String, String> transfer(ResultSet resultSet, ViewMode viewMode) {
    Map<String, String> article = new HashMap<String, String>();
    try {//from  w  w w .  j av  a 2 s. co m
        String id = resultSet.getString("id");
        article.put("id", id);
        if (viewMode == ViewMode.DYNAMIC) {
            article.put("url", ArticleHelper.generateDynamicPath(Integer.valueOf(id)));
        } else {
            article.put("url", ArticleHelper.generateStaticPath(Integer.valueOf(id)));
        }
        List<Map<String, String>> tags = DaoFactory.getDao(TagDao.class).getTags(Integer.valueOf(id));
        StringBuffer stringBuffer = new StringBuffer("");
        if (tags != null && tags.size() > 0) {
            for (int i = 0; i < tags.size(); i++) {
                Map<String, String> tag = tags.get(i);
                if (i > 0) {
                    stringBuffer.append(",");
                }
                stringBuffer.append(tag.get("tag_name"));
            }
        }
        article.put("tags", stringBuffer.toString());
        article.put("icon", resultSet.getString("icon"));
        article.put("subject", resultSet.getString("subject"));
        article.put("username", resultSet.getString("username"));
        Timestamp createDate = resultSet.getTimestamp("create_date");
        article.put("create_date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createDate));
        article.put("us_create_date", DateUtil.rfc822(createDate));
        article.put("status", resultSet.getString("status"));
        article.put("type", resultSet.getString("type"));
        article.put("access_times", resultSet.getString("access_times"));
        article.put("comment_times", resultSet.getString("comment_times"));

        article.put("good_times", resultSet.getString("good_times"));
        article.put("touch_times", resultSet.getString("touch_times"));
        article.put("funny_times", resultSet.getString("funny_times"));
        article.put("happy_times", resultSet.getString("happy_times"));
        article.put("anger_times", resultSet.getString("anger_times"));
        article.put("bored_times", resultSet.getString("bored_times"));
        article.put("water_times", resultSet.getString("water_times"));
        article.put("surprise_times", resultSet.getString("surprise_times"));
        String html = resultSet.getString("html");
        article.put("html", html);
        article.put("escapeHtml", StringUtil.escapeHtml(html));
        String content = resultSet.getString("content");
        article.put("content", content);
        article.put("summary", StringUtil.substring(content, 100));
        String subject = resultSet.getString("subject");
        article.put("short_subject", StringUtil.substring(subject, 10) + (subject.length() > 10 ? "..." : ""));
        article.put("common_subject", StringUtil.substring(subject, 15) + (subject.length() > 15 ? "..." : ""));
        putAllTimesHeight(article);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return article;
}

From source file:com.alfaariss.oa.engine.tgt.jdbc.JDBCTGTFactory.java

/**
 * Retrieve the TGT with the given id./* ww  w.  ja v  a2 s.co  m*/
 * @param id The TGT id.
 * @return The TGT, or null if a TGT with the given id does not exist.
 * @throws PersistenceException If retrieving fails.
 */
@SuppressWarnings("unchecked") //Serialize value can not be checked
public JDBCTGT retrieve(Object id) throws PersistenceException {
    if (id == null || !(id instanceof String))
        throw new IllegalArgumentException("Suplied id is empty or invalid");

    JDBCTGT tgt = null;
    Connection oConnection = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        oConnection = _oDataSource.getConnection();
        ps = oConnection.prepareStatement(_sSearchQuery);
        ps.setString(1, (String) id);
        rs = ps.executeQuery();
        if (rs.next()) {
            byte[] baUser = rs.getBytes(_sColumnUSER);
            tgt = new JDBCTGT(this, (IUser) Serialize.decode(baUser));
            tgt.setId((String) id);
            tgt.setTgtExpTime(rs.getTimestamp(_sColumnEXPIRATION).getTime());
            tgt.setAuthenticationProfile(
                    (AuthenticationProfile) Serialize.decode(rs.getBytes(_sColumnAUTHN_PROFILE)));
            tgt.setAuthNProfileIDs((List) Serialize.decode(rs.getBytes(_sColumnAUTHN_PROFILES)));
            tgt.setRequestorIDs((List) Serialize.decode(rs.getBytes(_sColumnREQUESTOR_IDS)));

            TGTAttributes oAttributes = (TGTAttributes) Serialize.decode(rs.getBytes(_sColumnATTRIBUTES));
            if (oAttributes != null)
                tgt.setAttributes(oAttributes);
        }
    } catch (SQLException e) {
        _logger.error("Could not execute search query", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } catch (ClassCastException e) {
        _logger.error("Could not decode, invalid class type", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } catch (Exception e) {
        _logger.error("Internal error during retrieval of tgt with id: " + id, e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } finally {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            _logger.debug("Could not close resultset", e);
        }
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            _logger.debug("Could not close statement", e);
        }
        try {
            if (oConnection != null)
                oConnection.close();
        } catch (SQLException e) {
            _logger.debug("Could not close connection", e);
        }
    }
    return tgt;
}

From source file:org.dcache.chimera.FsSqlDriver.java

private Stat toStat(ResultSet rs) throws SQLException {
    Stat stat = new Stat();
    stat.setIno(rs.getLong("inumber"));
    stat.setId(rs.getString("ipnfsid"));
    stat.setCrTime(rs.getTimestamp("icrtime").getTime());
    stat.setGeneration(rs.getLong("igeneration"));
    int rp = rs.getInt("iretention_policy");
    if (!rs.wasNull()) {
        stat.setRetentionPolicy(RetentionPolicy.valueOf(rp));
    }//from  w  ww  .  j  a v a  2 s  . com
    int al = rs.getInt("iaccess_latency");
    if (!rs.wasNull()) {
        stat.setAccessLatency(AccessLatency.valueOf(al));
    }
    stat.setSize(rs.getLong("isize"));
    stat.setATime(rs.getTimestamp("iatime").getTime());
    stat.setCTime(rs.getTimestamp("ictime").getTime());
    stat.setMTime(rs.getTimestamp("imtime").getTime());
    stat.setUid(rs.getInt("iuid"));
    stat.setGid(rs.getInt("igid"));
    stat.setMode(rs.getInt("imode") | rs.getInt("itype"));
    stat.setNlink(rs.getInt("inlink"));
    stat.setDev(17);
    stat.setRdev(13);
    return stat;
}

From source file:com.sfs.whichdoctor.dao.AccreditationDAOImpl.java

/**
 * Load accreditation./*from www.j a va  2 s.c o  m*/
 *
 * @param rs the rs
 *
 * @return the accreditation bean
 *
 * @throws SQLException the SQL exception
 */
private AccreditationBean loadAccreditation(final ResultSet rs) throws SQLException {

    AccreditationBean accreditation = new AccreditationBean();

    accreditation.setId(rs.getInt("AccreditationId"));
    accreditation.setGUID(rs.getInt("GUID"));
    accreditation.setReferenceGUID(rs.getInt("ReferenceGUID"));
    accreditation.setCore(rs.getBoolean("Core"));

    accreditation.setAccreditationClass(rs.getString("AccreditationClass"));
    accreditation.setAccreditationType(rs.getString("AccreditationType"));
    accreditation.setAbbreviation(rs.getString("AccreditationTypeAbbreviation"));

    accreditation.setSpecialtyType(rs.getString("SpecialtyTypeClass"));
    accreditation.setSpecialtyTypeAbbreviation(rs.getString("SpecialtyTypeAbbreviation"));
    accreditation.setSpecialtySubType(rs.getString("SpecialtyTypeName"));
    accreditation.setWeeksApproved(rs.getInt("WeeksApproved"));
    accreditation.setWeeksCertified(rs.getInt("WeeksCertified"));
    accreditation.setNote(rs.getString("Note"));
    try {
        accreditation.setAccreditationDate(rs.getDate("AccreditationDate"));
    } catch (Exception e) {
        dataLogger.debug("Error parsing AccreditationDate: " + e.getMessage());
    }

    accreditation.setActive(rs.getBoolean("Active"));
    try {
        accreditation.setCreatedDate(rs.getTimestamp("CreatedDate"));
    } catch (SQLException e) {
        dataLogger.debug("Error parsing CreatedDate: " + e.getMessage());
    }
    accreditation.setCreatedBy(rs.getString("CreatedBy"));
    try {
        accreditation.setModifiedDate(rs.getTimestamp("ModifiedDate"));
    } catch (SQLException e) {
        dataLogger.debug("Error parsing ModifiedDate: " + e.getMessage());
    }
    accreditation.setModifiedBy(rs.getString("ModifiedBy"));
    try {
        accreditation.setExportedDate(rs.getTimestamp("ExportedDate"));
    } catch (SQLException e) {
        dataLogger.debug("Error parsing ExportedDate: " + e.getMessage());
    }
    accreditation.setExportedBy(rs.getString("ExportedBy"));

    return accreditation;
}

From source file:com.sfs.whichdoctor.dao.BulkEmailDAOImpl.java

/**
 * Load bulk email.//from  ww w. j  av a2s. c  om
 *
 * @param rs the rs
 * @param loadDetails the load details
 * @return the bulk email bean
 * @throws SQLException the sQL exception
 */
private BulkEmailBean loadBulkEmail(final ResultSet rs, final BuilderBean loadDetails) throws SQLException {

    BulkEmailBean bulkEmail = new BulkEmailBean();

    bulkEmail.setId(rs.getInt("BulkEmailId"));
    bulkEmail.setGUID(rs.getInt("GUID"));
    bulkEmail.setEmailAddress(rs.getString("EmailAddress"));
    bulkEmail.setSenderName(rs.getString("SenderName"));
    bulkEmail.setAdditionalRecipients(rs.getString("AdditionalRecipients"));
    bulkEmail.setSubject(rs.getString("Subject"));
    bulkEmail.setPriority(rs.getInt("Priority"));
    bulkEmail.setAppendContact(rs.getBoolean("AppendContact"));
    bulkEmail.setAppendLogo(rs.getBoolean("AppendLogo"));
    bulkEmail.setAppendPrivacy(rs.getBoolean("AppendPrivacy"));
    bulkEmail.setDeliverOutOfHours(rs.getBoolean("DeliverOutOfHours"));
    bulkEmail.setMessage(rs.getString("Message"));
    bulkEmail.setEmailClass(rs.getString("EmailClass"));
    bulkEmail.setEmailType(rs.getString("EmailType"));

    bulkEmail.setSentCount(rs.getInt("SentCount"));
    bulkEmail.setFailedCount(rs.getInt("FailedCount"));
    bulkEmail.setPendingCount(rs.getInt("PendingCount"));

    bulkEmail.setActive(rs.getBoolean("Active"));
    try {
        bulkEmail.setCreatedDate(rs.getTimestamp("CreatedDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage());
    }
    bulkEmail.setCreatedBy(rs.getString("CreatedBy"));
    try {
        bulkEmail.setModifiedDate(rs.getTimestamp("ModifiedDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage());
    }
    bulkEmail.setModifiedBy(rs.getString("ModifiedBy"));

    // Load user details from DB
    UserBean user = new UserBean();
    user.setDN(rs.getString("CreatedBy"));
    user.setPreferredName(rs.getString("CreatedFirstName"));
    user.setLastName(rs.getString("CreatedLastName"));
    bulkEmail.setCreatedUser(user);

    UserBean modified = new UserBean();
    modified.setDN(rs.getString("ModifiedBy"));
    modified.setPreferredName(rs.getString("ModifiedFirstName"));
    modified.setLastName(rs.getString("ModifiedLastName"));
    bulkEmail.setModifiedUser(modified);

    if (loadDetails.getBoolean("EMAIL_RECIPIENTS")) {
        try {
            bulkEmail.setEmailRecipients(this.emailRecipientDAO.load(bulkEmail.getGUID()));
        } catch (Exception e) {
            dataLogger.error("Error loading email recipients: " + e.getMessage());
        }
    }
    return bulkEmail;
}

From source file:PVGraph.java

public java.util.List<DayData> getDayData(int year, int month, int day) {
    Statement stmt = null;//ww w  .j a v a 2s .c om
    String query = "select * from DayData where year(DateTime) = " + year + " and month(DateTime) = " + month
            + " and dayofmonth(DateTime) = " + day + " order by DateTime";
    Map<String, DayData> result = new HashMap<String, DayData>();
    try {
        getDatabaseConnection();
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        long lastTime = 0;
        int lastPower = 0;
        while (rs.next()) {
            String serial = rs.getString("serial");
            DayData dd = result.get(serial);
            if (dd == null) {
                dd = new DayData();
                dd.serial = serial;
                dd.inverter = rs.getString("inverter");
                dd.startTotalPower = rs.getDouble("ETotalToday");
                result.put(serial, dd);
            }
            Timestamp currentTime = rs.getTimestamp("DateTime");
            int currentPower = rs.getInt("CurrentPower");
            if (lastTime != 0) {
                long fiveMinutesAfterLastTime = lastTime + 300 * 1000;
                long fiveMinutesBeforeCurrentTime = currentTime.getTime() - 300 * 1000;
                if (currentTime.getTime() > fiveMinutesAfterLastTime) {
                    for (long t = fiveMinutesAfterLastTime; t <= fiveMinutesBeforeCurrentTime; t += 300
                            * 1000) {
                        //System.err.println("Adding zero power at " + new Timestamp(t));
                        dd.times.add(new Timestamp(t));
                        dd.powers.add(0);
                    }
                }
            }
            dd.times.add(currentTime);
            dd.powers.add(currentPower);
            dd.endTotalPower = rs.getDouble("ETotalToday");
            lastTime = currentTime.getTime();
            lastPower = currentPower;
        }
    } catch (SQLException e) {
        System.err.println("Query failed: " + e.getMessage());
    } finally {
        try {
            stmt.close();
        } catch (SQLException e) {
            // relax
        }
    }
    return new java.util.ArrayList<DayData>(result.values());
}