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:com.concursive.connect.web.modules.plans.dao.RequirementIndexer.java

/**
 * Given a database and a Lucene writer, this method will add content to the
 * searchable index/*from w ww.  j  a  va  2 s  .  c  o m*/
 *
 * @param writer  Description of the Parameter
 * @param db      Description of the Parameter
 * @param context
 * @throws SQLException Description of the Exception
 * @throws IOException  Description of the Exception
 */
public void add(IIndexerService writer, Connection db, IndexerContext context)
        throws SQLException, IOException {
    int count = 0;
    PreparedStatement pst = db.prepareStatement(
            "SELECT requirement_id, project_id, shortdescription, description, submittedby, departmentby, modified "
                    + "FROM project_requirements " + "WHERE requirement_id > -1 ");
    ResultSet rs = pst.executeQuery();
    while (rs.next() && context.getEnabled()) {
        ++count;
        // read the record
        Requirement requirement = new Requirement();
        requirement.setId(rs.getInt("requirement_id"));
        requirement.setProjectId(rs.getInt("project_id"));
        requirement.setShortDescription(rs.getString("shortdescription"));
        requirement.setDescription(rs.getString("description"));
        requirement.setSubmittedBy(rs.getString("submittedBy"));
        requirement.setDepartmentBy(rs.getString("departmentBy"));
        requirement.setModified(rs.getTimestamp("modified"));
        // add the document
        writer.indexAddItem(requirement, false);
    }
    rs.close();
    pst.close();
    LOG.info("RequirementIndexer-> Finished: " + count);
}

From source file:dao.DirBlobSearchQuery.java

/**
 * This method lists all the results for the search text from directories
 * @param conn the connection/*from   ww w .j  a v a 2s. c om*/
 * @param collabrumId the collabrumid
 * @return HashSet the set that has the list of moderators for these collabrums.
 * @throws BaseDaoException - when error occurs
 **/
public HashSet run(Connection conn, String sString) throws BaseDaoException {

    if ((RegexStrUtil.isNull(sString) || conn == null)) {
        return null;
    }

    /*        StringBuffer sb = new StringBuffer("select blobtype, dirblob.directoryid, entrydate, dirblob.entryid, btitle from dirblob left join dirblobtags on dirblob.entryid=dirblobtags.entryid where ");
    */
    StringBuffer sb = new StringBuffer(
            "select distinct d1.btitle, d1.mimetype, d1.entryid, d1.directoryid from dirblob d1, dirblobtags d2 where ");
    ArrayList columns = new ArrayList();
    columns.add("d1.btitle");
    columns.add("d2.usertags");
    sb.append(sqlSearch.getConstraint(columns, sString));
    sb.append(" and d1.entryid=d2.entryid and d1.directoryid=d2.directoryid");
    try {
        PreparedStatement stmt = conn.prepareStatement(sb.toString());
        ResultSet rs = stmt.executeQuery();

        Vector columnNames = null;
        Photo photo = null;
        HashSet pendingSet = new HashSet();

        if (rs != null) {
            columnNames = dbutils.getColumnNames(rs);
        }

        while (rs.next()) {
            photo = (Photo) eop.newObject(DbConstants.PHOTO);
            for (int j = 0; j < columnNames.size(); j++) {
                if (((String) (columnNames.elementAt(j))).equalsIgnoreCase(DbConstants.ENTRY_DATE)) {
                    try {
                        photo.setValue(DbConstants.ENTRY_DATE,
                                GlobalConst.dncalendar.getDisplayDate(rs.getTimestamp(DbConstants.ENTRY_DATE)));
                    } catch (ParseException e) {
                        throw new BaseDaoException("could not parse the date for entrydate in dirblob "
                                + rs.getTimestamp(DbConstants.ENTRY_DATE), e);
                    }
                } else {
                    photo.setValue((String) columnNames.elementAt(j),
                            (String) rs.getString((String) columnNames.elementAt(j)));
                }
            }
            pendingSet.add(photo);
        }
        return pendingSet;
    } catch (Exception e) {
        throw new BaseDaoException("Error occured while executing search dirblob run query " + sb.toString(),
                e);
    }
}

From source file:au.edu.jcu.fascinator.plugin.harvester.directory.DerbyCache.java

private long getLastModified(String oid) {
    try {/* w w  w.  j  a  v  a2s  .c  o m*/
        PreparedStatement sql = connection()
                .prepareStatement("SELECT lastModified FROM " + BASIC_TABLE + " WHERE oid = ? AND cacheId = ?");

        // Prepare and execute
        sql.setString(1, oid);
        sql.setString(2, cacheId);
        ResultSet result = sql.executeQuery();

        // Build response
        Timestamp ts = null;
        if (result.next()) {
            ts = result.getTimestamp("lastModified");
        }
        close(result);
        close(sql);

        if (ts == null) {
            return -1;
        } else {
            return ts.getTime();
        }
    } catch (SQLException ex) {
        log.error("Error querying last modified date: ", ex);
        return -1;
    }
}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

@Test
public void testObjectTimestamp() throws Exception {
    Statement stmt = con.createStatement();
    java.util.Date now = new java.util.Date();

    // Create the target Column family
    //String createCF = "CREATE COLUMNFAMILY t74 (id BIGINT PRIMARY KEY, col1 TIMESTAMP)";        
    String createCF = "CREATE COLUMNFAMILY t74 (id BIGINT PRIMARY KEY, col1 TIMESTAMP)";

    stmt.execute(createCF);//from   www . j a  va 2s  . c o m
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));

    Statement statement = con.createStatement();

    String insert = "INSERT INTO t74 (id, col1) VALUES (?, ?);";

    PreparedStatement pstatement = con.prepareStatement(insert);
    pstatement.setLong(1, 1L);
    pstatement.setObject(2, new Timestamp(now.getTime()), Types.TIMESTAMP);
    pstatement.execute();

    ResultSet result = statement.executeQuery("SELECT * FROM t74;");

    assertTrue(result.next());
    assertEquals(1L, result.getLong(1));

    // try reading Timestamp directly
    Timestamp stamp = result.getTimestamp(2);
    assertEquals(now, stamp);

    // try reading Timestamp as an object
    stamp = result.getObject(2, Timestamp.class);
    assertEquals(now, stamp);

    System.out.println(resultToDisplay(result, 74, "current date"));

}

From source file:com.nabla.wapp.server.json.SqlColumn.java

public void write(final ResultSet rs, int column, final JSONObject record) throws SQLException {
    switch (type) {
    case Types.BIGINT:
    case Types.INTEGER:
    case Types.SMALLINT:
    case Types.TINYINT:
        record.put(label, rs.getInt(column));
        break;/*from   ww w .  j  a  v a2 s. co  m*/
    case Types.BOOLEAN:
    case Types.BIT:
        record.put(label, rs.getBoolean(column));
        break;
    case Types.DATE:
        final Date dt = rs.getDate(column);
        if (rs.wasNull())
            record.put(label, null);
        else
            record.put(label, new JSonDate(dt));
        return;
    case Types.TIMESTAMP:
        final Timestamp tm = rs.getTimestamp(column);
        if (rs.wasNull())
            record.put(label, null);
        else
            record.put(label, timeStampFormat.format(tm));
        return;
    case Types.DOUBLE:
        record.put(label, rs.getDouble(column));
        break;
    case Types.FLOAT:
        record.put(label, rs.getFloat(column));
        break;
    case Types.NULL:
        record.put(label, null);
        return;
    default:
        record.put(label, rs.getString(column));
        break;
    }
    if (rs.wasNull())
        record.put(label, null);
}

From source file:edu.jhu.pha.vospace.rest.TransfersController.java

/**
 * Returns the transfers queue//from  w w w. ja  va  2 s  .c o  m
 * @return transfer representation
 */
@GET
@Produces(MediaType.TEXT_PLAIN)
@RolesAllowed({ "user" })
public String getTransfersQueue() {
    final SciDriveUser user = ((SciDriveUser) security.getUserPrincipal());
    return DbPoolServlet.goSql("Get transfers queue",
            "select id, state, direction, starttime, endtime, target from jobs where login = ?",
            new SqlWorker<String>() {
                @Override
                public String go(Connection conn, PreparedStatement stmt) throws SQLException {
                    StringBuffer resultBuf = new StringBuffer();
                    resultBuf.append("id, state, direction, starttime, endtime, path\n");

                    stmt.setString(1, user.getName());

                    ResultSet resSet = stmt.executeQuery();
                    while (resSet.next()) {
                        resultBuf.append(resSet.getString(1) + ", ");
                        resultBuf.append(resSet.getString(2) + ", ");
                        resultBuf.append(resSet.getString(3) + ", ");
                        resultBuf.append((null != resSet.getTimestamp(4) ? resSet.getTimestamp(4) : "") + ", ");
                        resultBuf.append((null != resSet.getTimestamp(5) ? resSet.getTimestamp(5) : "") + ", ");
                        resultBuf.append(resSet.getString(6));
                        resultBuf.append("\n");
                    }
                    return resultBuf.toString();
                }
            });
}

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.IdeaInstanceDAO.java

@Override
public IdeaInstance loadIdeaInstance(String code, Collection<Integer> ideaStatus) {
    IdeaInstance ideainstance = null;// w w w.  ja  va  2 s.  c o  m
    Connection conn = null;
    PreparedStatement stat = null;
    ResultSet res = null;
    try {
        conn = this.getConnection();
        stat = conn.prepareStatement(LOAD_IDEAINSTANCE);
        int index = 1;
        stat.setString(index++, code);
        res = stat.executeQuery();
        if (res.next()) {
            ideainstance = new IdeaInstance();
            ideainstance.setCode(res.getString("code"));
            Timestamp createdatValue = res.getTimestamp("createdat");
            if (null != createdatValue) {
                ideainstance.setCreatedat(new Date(createdatValue.getTime()));
            }
        }
        if (null != ideainstance) {
            List<String> groups = this.loadIdeaInstanceGroups(code, conn);
            ideainstance.setGroups(groups);
            List<Integer> ideas = this.loadIdeaInstanceIdeas(code, ideaStatus, conn);
            ideainstance.setChildren(ideas);
        }

    } catch (Throwable t) {
        _logger.error("Error loading ideainstance with code {}", code, t);
        throw new RuntimeException("Error loading ideainstance", t);
    } finally {
        closeDaoResources(res, stat, conn);
    }
    return ideainstance;
}

From source file:org.gridobservatory.greencomputing.dao.MachineDao.java

@Override
public Machine findById(BigInteger id) {
    return this.getJdbcTemplate().queryForObject(
            "select machine_id, room_id, motherboard_id, middleware_id, date_created, date_retired from machine where machine_id = ?",
            new Object[] { id }, new RowMapper<Machine>() {
                @Override/*from  w w w . j  a va  2  s  .  c  o m*/
                public Machine mapRow(ResultSet rs, int rowNum) throws SQLException {
                    int i = 1;
                    Machine machine = new Machine();
                    machine.setMachineID(rs.getBigDecimal(i++).toBigIntegerExact());

                    machine.setRoom(new Room());
                    machine.getRoom().setRoomID(rs.getBigDecimal(i++).toBigIntegerExact());

                    machine.setMotherboard(new Motherboard());
                    machine.getMotherboard().setMotherboardID(rs.getBigDecimal(i++).toBigIntegerExact());

                    machine.setMiddleware(new Middleware());
                    machine.getMiddleware().setMiddlewareID(rs.getBigDecimal(i++).toBigIntegerExact());

                    machine.setDateCreated(BigInteger.valueOf(rs.getTimestamp(i++).getTime()));

                    return machine;
                }
            });
}

From source file:com.sfs.dao.FieldMapDAOImpl.java

/**
 * Load field map./*from  ww  w .  java2s . c o  m*/
 *
 * @param rs the rs
 *
 * @return the field map bean
 *
 * @throws SQLException the SQL exception
 */
private FieldMapBean loadFieldMap(final ResultSet rs) throws SQLException {

    FieldMapBean fieldMap = new FieldMapBean();

    // Create field map bean and fill with dataset info.
    fieldMap.setFieldMapId(rs.getInt("Id"));
    fieldMap.setMapClass(rs.getString("MapClass"));
    fieldMap.setMapType(rs.getString("MapType"));
    fieldMap.setFieldType(rs.getString("FieldType"));
    fieldMap.setName(rs.getString("FieldName"));
    fieldMap.setIndex(rs.getInt("FieldNo"));
    fieldMap.setFieldType(rs.getString("FieldType"));
    fieldMap.setDescription(rs.getString("Description"));
    fieldMap.setObjectType(rs.getString("ObjectType"));

    try {
        fieldMap.setCreated(rs.getTimestamp("Created"));
    } catch (SQLException sqe) {
        dataLogger.info("Could not load Created date: " + sqe.getMessage());
    }
    fieldMap.setCreatedBy(rs.getString("CreatedBy"));
    try {
        fieldMap.setModified(rs.getTimestamp("Modified"));
    } catch (SQLException sqe) {
        dataLogger.info("Could not load Modified date: " + sqe.getMessage());
    }
    fieldMap.setModifiedBy(rs.getString("ModifiedBy"));

    if (fieldMap.getCreatedBy() != null && this.userDAO != null) {
        try {
            fieldMap.setCreatedByUser(this.userDAO.loadCached(fieldMap.getCreatedBy()));
        } catch (Exception e) {
            dataLogger.info(
                    "Could not load CreatedBy UserBean for " + "FieldMapId = " + fieldMap.getFieldMapId());
        }
    }
    if (fieldMap.getModifiedBy() != null && this.userDAO != null) {
        try {
            fieldMap.setModifiedByUser(this.userDAO.loadCached(fieldMap.getModifiedBy()));
        } catch (Exception e) {
            dataLogger.info(
                    "Could not load ModifiedBy UserBean for " + "FieldMapId = " + fieldMap.getFieldMapId());
        }
    }
    return fieldMap;
}

From source file:com.concursive.connect.web.modules.common.social.rating.dao.Rating.java

/**
 * @param rs          the resultset to build the record from
 * @param uniqueField//w ww.  j  a  va 2s  . c o  m
 */
private void buildRecord(ResultSet rs, String primaryKeyField, String uniqueField, boolean hasInappropriate)
        throws SQLException {
    id = rs.getInt(primaryKeyField);
    objectId = rs.getInt(uniqueField);
    rating = DatabaseUtils.getInt(rs, "rating");
    if (hasInappropriate) {
        inappropriate = rs.getBoolean("inappropriate");
    }
    entered = rs.getTimestamp("entered");
    enteredby = DatabaseUtils.getInt(rs, "enteredby");
    projectId = DatabaseUtils.getInt(rs, "project_id");
}