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:org.jfree.data.jdbc.JDBCPieDataset.java

/**
 *  ExecuteQuery will attempt execute the query passed to it against the
 *  existing database connection.  If no connection exists then no action
 *  is taken./*ww w .jav a2s .com*/
 *  The results from the query are extracted and cached locally, thus
 *  applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param  query  the query to be executed
 * @param  con  the connection the query is to be executed against
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    Statement statement = null;
    ResultSet resultSet = null;

    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnCount = metaData.getColumnCount();
        if (columnCount != 2) {
            throw new SQLException("Invalid sql generated.  PieDataSet requires 2 columns only");
        }

        int columnType = metaData.getColumnType(2);
        double value = Double.NaN;
        while (resultSet.next()) {
            Comparable key = resultSet.getString(1);
            switch (columnType) {
            case Types.NUMERIC:
            case Types.REAL:
            case Types.INTEGER:
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.DECIMAL:
            case Types.BIGINT:
                value = resultSet.getDouble(2);
                setValue(key, value);
                break;

            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP:
                Timestamp date = resultSet.getTimestamp(2);
                value = date.getTime();
                setValue(key, value);
                break;

            default:
                System.err.println("JDBCPieDataset - unknown data type");
                break;
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info

    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                System.err.println("JDBCPieDataset: swallowing exception.");
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                System.err.println("JDBCPieDataset: swallowing exception.");
            }
        }
    }
}

From source file:hoot.services.writers.review.ReviewPrepareDbWriter.java

protected Map<Long, Object> getParseableElementRecords(final long mapId, final ElementType elementType,
        final int limit, final int offset) throws InstantiationException, IllegalAccessException,
        ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
    Map<Long, Object> retMap = new LinkedHashMap<Long, Object>();
    final Element prototype = ElementFactory.getInstance().create(mapId, elementType, conn);
    String tableName = prototype.getElementTable().getTableName();
    String idFieldName = ColumnMetadata.getColumnMetadata(prototype.getElementIdField()).getName();

    String POSTGRESQL_DRIVER = "org.postgresql.Driver";
    Statement stmt = null;/*from  w  ww  .  jav  a  2 s .com*/
    try {
        Class.forName(POSTGRESQL_DRIVER);

        stmt = conn.createStatement();

        String sql = "select * from " + tableName + "_" + mapId + " where " + "EXIST(tags, 'uuid') = TRUE "
                + " order by " + idFieldName + " limit " + limit + " offset " + offset;
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        while (rs.next()) {

            if (elementType == ElementType.Node) {
                CurrentNodes nodes = new CurrentNodes();
                nodes.setId(rs.getLong("id"));

                nodes.setLatitude(rs.getInt("latitude"));
                nodes.setLongitude(rs.getInt("longitude"));
                nodes.setChangesetId(rs.getLong("changeset_id"));
                nodes.setVisible(rs.getBoolean("visible"));
                nodes.setTimestamp(rs.getTimestamp("timestamp"));
                nodes.setTile(rs.getLong("tile"));
                nodes.setVersion(rs.getLong("version"));
                nodes.setTags(rs.getObject("tags"));
                retMap.put(nodes.getId(), nodes);
            } else if (elementType == ElementType.Way) {
                CurrentWays ways = new CurrentWays();
                ways.setId(rs.getLong("id"));

                ways.setChangesetId(rs.getLong("changeset_id"));
                ways.setVisible(rs.getBoolean("visible"));
                ways.setTimestamp(rs.getTimestamp("timestamp"));
                ways.setVersion(rs.getLong("version"));
                ways.setTags(rs.getObject("tags"));
                retMap.put(ways.getId(), ways);
            } else if (elementType == ElementType.Relation) {
                CurrentRelations rel = new CurrentRelations();
                rel.setId(rs.getLong("id"));

                rel.setChangesetId(rs.getLong("changeset_id"));
                rel.setVisible(rs.getBoolean("visible"));
                rel.setTimestamp(rs.getTimestamp("timestamp"));
                rel.setVersion(rs.getLong("version"));
                rel.setTags(rs.getObject("tags"));
                retMap.put(rel.getId(), rel);
            }
        }
        rs.close();

    } catch (Exception e) {
        //throw new Exception("Error inserting node.");
    }

    finally {
        //finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {

        } // nothing we can do

    } //end try

    return retMap;
}

From source file:hoot.services.writers.review.ReviewPrepareDbWriter.java

protected Map<Long, Object> getReviewableElementRecords(final long mapId, final ElementType elementType,
        final int limit, final int offset) throws InstantiationException, IllegalAccessException,
        ClassNotFoundException, NoSuchMethodException, InvocationTargetException {

    Map<Long, Object> retMap = new LinkedHashMap<Long, Object>();
    final Element prototype = ElementFactory.getInstance().create(mapId, elementType, conn);

    String tableName = prototype.getElementTable().getTableName();
    String idFieldName = ColumnMetadata.getColumnMetadata(prototype.getElementIdField()).getName();

    String POSTGRESQL_DRIVER = "org.postgresql.Driver";
    Statement stmt = null;//from   w  w w.  j  a v a  2s  .c o m
    try {
        Class.forName(POSTGRESQL_DRIVER);

        stmt = conn.createStatement();

        String sql = "select * from " + tableName + "_" + mapId + " where "
                + " tags->'hoot:review:needs' = 'yes' " + " order by " + idFieldName + " limit " + limit
                + " offset " + offset;
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        while (rs.next()) {

            if (elementType == ElementType.Node) {
                CurrentNodes nodes = new CurrentNodes();
                nodes.setId(rs.getLong("id"));

                nodes.setLatitude(rs.getInt("latitude"));
                nodes.setLongitude(rs.getInt("longitude"));
                nodes.setChangesetId(rs.getLong("changeset_id"));
                nodes.setVisible(rs.getBoolean("visible"));
                nodes.setTimestamp(rs.getTimestamp("timestamp"));
                nodes.setTile(rs.getLong("tile"));
                nodes.setVersion(rs.getLong("version"));
                nodes.setTags(rs.getObject("tags"));
                retMap.put(nodes.getId(), nodes);
            } else if (elementType == ElementType.Way) {
                CurrentWays ways = new CurrentWays();
                ways.setId(rs.getLong("id"));

                ways.setChangesetId(rs.getLong("changeset_id"));
                ways.setVisible(rs.getBoolean("visible"));
                ways.setTimestamp(rs.getTimestamp("timestamp"));
                ways.setVersion(rs.getLong("version"));
                ways.setTags(rs.getObject("tags"));
                retMap.put(ways.getId(), ways);
            } else if (elementType == ElementType.Relation) {
                CurrentRelations rel = new CurrentRelations();
                rel.setId(rs.getLong("id"));

                rel.setChangesetId(rs.getLong("changeset_id"));
                rel.setVisible(rs.getBoolean("visible"));
                rel.setTimestamp(rs.getTimestamp("timestamp"));
                rel.setVersion(rs.getLong("version"));
                rel.setTags(rs.getObject("tags"));
                retMap.put(rel.getId(), rel);
            }
        }
        rs.close();

    } catch (Exception e) {
        //throw new Exception("Error inserting node.");
    }

    finally {
        //finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {

        } // nothing we can do

    } //end try

    return retMap;

}

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

/**
 * Load online tool bean from the result set.
 *
 * @param rs the rs/*from ww  w.  j a v  a2 s  .c  o  m*/
 * @return the online tool bean
 * @throws SQLException the sQL exception
 */
private OnlineToolBean loadOnlineTool(final ResultSet rs) throws SQLException {

    OnlineToolBean onlineTool = new OnlineToolBean();

    onlineTool.setId(rs.getInt("OnlineToolId"));
    onlineTool.setReferenceGUID(rs.getInt("ReferenceGUID"));
    onlineTool.setRotationGUID(rs.getInt("RotationGUID"));
    onlineTool.setRotationOverridden(rs.getBoolean("RotationOverridden"));
    onlineTool.setName(rs.getString("Name"));
    onlineTool.setShortName(rs.getString("ShortName"));
    onlineTool.setCourse(rs.getString("Course"));
    onlineTool.setStatus(rs.getString("Status"));
    onlineTool.setYear(rs.getInt("Year"));
    onlineTool.setRotationName(rs.getString("RotationName"));

    try {
        onlineTool.setStartDate(rs.getTimestamp("StartDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading StartDate: " + sqe.getMessage());
    }

    try {
        onlineTool.setEndDate(rs.getTimestamp("EndDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading EndDate: " + sqe.getMessage());
    }

    try {
        onlineTool.setSubmitted(rs.getTimestamp("Submitted"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading SubmittedDate: " + sqe.getMessage());
    }

    try {
        onlineTool.setCompleted(rs.getTimestamp("Completed"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading CompletedDate: " + sqe.getMessage());
    }

    return onlineTool;
}

From source file:edu.ku.brc.specify.conversion.ConvertMiscData.java

/**
 * @param oldDBConn//  w ww  .  j  ava  2s  . c  o m
 * @param newDBConn
 * @param disciplineID
 * @return
 */
public static boolean convertKUInvertsObsData(final Connection oldDBConn, final Connection newDBConn) {
    Timestamp now = new Timestamp(System.currentTimeMillis());

    IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
    IdMapperIFace coMapper = IdMapperMgr.getInstance().addTableMapper("collectionobjectcatalog",
            "CollectionObjectCatalogID", false);

    PreparedStatement pStmt1 = null;
    PreparedStatement pStmt2 = null;
    PreparedStatement pStmt3 = null;
    try {
        pStmt1 = newDBConn.prepareStatement(
                "INSERT INTO collectionobjectattribute (Remarks, Text1, Number1, CollectionMemberID, TimestampCreated, TimestampModified, Version) VALUES(?,?,?,?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        pStmt2 = newDBConn.prepareStatement(
                "UPDATE collectionobjectattribute SET Remarks=?, Text1=?, Number1=? WHERE CollectionObjectAttributeID = ?");

        pStmt3 = newDBConn.prepareStatement(
                "UPDATE collectionobject SET CollectionObjectAttributeID=? WHERE CollectionObjectID = ?");

        int cnt = 0;
        String sql = " SELECT BiologicalObjectID, Remarks, Description, Count, TimestampCreated, TimestampModified FROM observation WHERE (Remarks IS NOT NULL) OR (Description IS NOT NULL) OR (Count IS NOT NULL)";
        Statement stmt = oldDBConn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            int oldCOId = rs.getInt(1);
            Integer newCOId = coMapper.get(oldCOId);
            if (newCOId != null) {
                sql = "SELECT CollectionObjectAttributeID, CollectionMemberID FROM collectionobject WHERE CollectionObjectID = "
                        + newCOId;
                Object[] row = BasicSQLUtils.getRow(sql);
                if (row == null || row.length == 0) {
                    log.error("Couldn't get record for  newCOId " + newCOId);
                    continue;
                }

                Integer newCOAId = (Integer) row[0];
                Integer collMemId = (Integer) row[1];

                if (newCOAId != null) // Do Update
                {
                    pStmt2.setString(1, rs.getString(2));
                    pStmt2.setString(2, rs.getString(3));
                    pStmt2.setInt(3, rs.getInt(4));
                    pStmt2.setInt(4, newCOAId);
                    int rv = pStmt2.executeUpdate();
                    if (rv == 0) {
                        System.err.println("Error updating newCOAId " + newCOAId);
                    }

                } else // Do Insert
                {
                    Timestamp ts = rs.getTimestamp(5);
                    if (ts == null) {
                        ts = now;
                    }
                    pStmt1.setString(1, rs.getString(2));
                    pStmt1.setString(2, rs.getString(3));
                    pStmt1.setInt(3, rs.getInt(4));
                    pStmt1.setInt(4, collMemId);
                    pStmt1.setTimestamp(5, ts);
                    pStmt1.setTimestamp(6, rs.getTimestamp(6));
                    pStmt1.setInt(7, 1);

                    int rv = pStmt1.executeUpdate();
                    newCOAId = BasicSQLUtils.getInsertedId(pStmt1);
                    if (rv == 0) {
                        System.err.println("Error inserting newCOAId " + newCOAId);
                    }
                }

                pStmt3.setInt(1, newCOAId);
                pStmt3.setInt(2, newCOId);
                int rv = pStmt3.executeUpdate();
                if (rv == 0) {
                    System.err.println("Error updating newCOId " + newCOId);
                }

                cnt++;

            } else {
                log.error("No mapped CO for Obs.BiologicalObjectID " + oldCOId);
            }
        }
        rs.close();
        stmt.close();

        System.out.println(String.format("Updated %d ColObj Records", cnt));

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            if (pStmt1 != null)
                pStmt1.close();
            if (pStmt2 != null)
                pStmt2.close();
            if (pStmt3 != null)
                pStmt3.close();

        } catch (Exception ex) {
        }
    }

    return false;
}

From source file:com.webpagebytes.wpbsample.database.WPBDatabase.java

public DepositWithdrawal getDepositOrWithdrawal(long id) throws SQLException {
    Connection connection = getConnection();
    PreparedStatement statement = null;
    try {//from   w  w  w  . j ava 2 s  . co m
        statement = connection.prepareStatement(GET_ACCOUNTOPERATIONS_STATEMENT);
        statement.setLong(1, id);
        ResultSet rs = statement.executeQuery();
        if (rs.next()) {
            DepositWithdrawal operation = new DepositWithdrawal();
            operation.setId(id);
            operation.setUser_id(rs.getInt(2));
            int type = rs.getInt(3);
            if (type == ACCOUNT_OPERATION_DEPOSIT) {
                operation.setType(OperationType.DEPOSIT);
            } else if (type == ACCOUNT_OPERATION_WITHDRAWAL) {
                operation.setType(OperationType.WITHDRAWAL);
            } else {
                return null;
            }
            operation.setDate(rs.getTimestamp(5));
            operation.setAmount(rs.getLong(4));
            return operation;
        } else {
            return null;
        }
    } catch (SQLException e) {
        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:com.snowy.data.java

public ArrayList<ArrayList<String>> retriveChallenges() {
    ArrayList<ArrayList<String>> res = new ArrayList<>();
    try {//from www.  j a  va2s  .c  o  m

        String uname = this.getUsernameFromToken();
        PreparedStatement ps = con.prepareStatement(
                "select requestor,requested,timestamp,accepted,RequestId from gamerequest where requestor = (select user_id from users where Username=?) or requested = (select user_id from users where Username=?) and timestamp >subdate(current_timestamp, interval 2 hour)");
        ps.setString(1, uname);
        ps.setString(2, uname);
        //PreparedStatement pss =con.prepareStatement("select Username from users where user_id=?");

        ResultSet rs = ps.executeQuery();
        rs.last();
        if (rs.getRow() > 0) {
            rs.beforeFirst();
            while (rs.next()) {

                ArrayList<String> al = new ArrayList<>();
                al.add(this.getUsernameFromId(rs.getInt("requestor")));
                al.add(this.getUsernameFromId(rs.getInt("requested")));
                al.add(String.valueOf(rs.getTimestamp("timestamp").getTime()));
                al.add(rs.getInt("accepted") + "");
                //al.add(rs.getInt("gameCreated")+"");
                al.add(rs.getInt("RequestId") + "");
                res.add(al);
            }
        }
        //ps.close();
        //rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex);
    }
    return res;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.dao.jdbc.QuartzJobHistoryQueriesImpl.java

public QuartzJobHistoryQueriesImpl() {

    quartzJobHistoryRowMapper = new ParameterizedRowMapper<QuartzJobHistory>() {

        public QuartzJobHistory mapRow(final ResultSet resultSet, final int i) throws SQLException {

            final Long jobWSSubmissionDateAsLong = resultSet.getLong(QuartzJobHistory.JOB_WS_SUBMISSION_DATE);
            Date jobWSSubmissionDate = null;

            // if 0L is found, it means the job was not submitted through the web service (and converting that would give us The Epoch ...)
            if (jobWSSubmissionDateAsLong != 0L) {
                jobWSSubmissionDate = new Date(jobWSSubmissionDateAsLong);
            }/*ww w  .j  a v  a  2 s .c om*/

            final QuartzJobHistory quartzJobHistory = new QuartzJobHistory(resultSet.getString(JOB_NAME),
                    resultSet.getString(JOB_GROUP), resultSet.getDate(FIRE_TIME),
                    QuartzJobStatus.valueOf(resultSet.getString(STATUS)), resultSet.getDate(LAST_UPDATED),
                    resultSet.getString(QuartzJobHistory.LINK_TEXT),
                    Long.parseLong(resultSet.getString(QuartzJobHistory.ESTIMATED_UNCOMPRESSED_SIZE)),
                    jobWSSubmissionDate);
            quartzJobHistory.setQueueName(resultSet.getString(QUEUE_NAME));
            quartzJobHistory.setEnqueueDate(resultSet.getTimestamp(TIME_ENQUEUED));
            return quartzJobHistory;
        }
    };
}

From source file:com.commander4j.db.JDBDespatch.java

public void getPropertiesfromResultSet(ResultSet rs) {
    try {//from  ww  w . j a  v  a  2  s  .c  om
        clear();

        setDespatchNo(rs.getString("despatch_no"));
        setDespatchDate(rs.getTimestamp("despatch_date"));
        setLocationIDFrom(rs.getString("location_id_from"));
        setLocationIDTo(rs.getString("location_id_to"));
        setStatus(rs.getString("status"));
        setTrailer(rs.getString("trailer"));
        setLoadNo(rs.getString("load_no"));
        setHaulier(rs.getString("haulier"));
        setTotalPallets(rs.getInt("total_pallets"));
        setTransactionRef(rs.getLong("transaction_ref"));
        setUserID(rs.getString("user_id"));
        setJourneyRef(rs.getString("journey_ref"));
        setJourneyRefOLD(rs.getString("journey_ref"));
    } catch (SQLException e) {
        setErrorMessage(e.getMessage());
    }
}