java - 如何判断 Java 中 Postgres 的时间戳是否为空

标签 java postgresql

下面的代码是我接触过的后端 REST 服务的一个片段。我想知道如何判断我得到的时间戳是否为空。我通过反复试验了解到,如果 Postgres 数据库中的时间戳为 null,当我将它引入 Java 时,如果它为 null,它将在当前操作时实例化为新的 DateTime。如何根据模型数据动态检查获取和设置空值?

public List<SubscriptionEntityModel> getAllSubscriptions(PagingInfoDomainModel paging) throws Exception {
    Database db = new Database();

    String stmt = "{call sp_subscriptions_get_all(?, ?)}";

    if(AppConfig.data.isDebug) {
        logger.debug("Running database operation.. " + stmt);
    }

    CallableStatement sproc = db.dbEndpoint.prepareCall(stmt);
    sproc.setInt(1, paging.pageCurrent);
    sproc.setInt(2, paging.pageItemCount);

    ResultSet rs = sproc.executeQuery();

    List<SubscriptionEntityModel> subscriptions = new ArrayList<SubscriptionEntityModel>();
    while(rs.next()) {
        SubscriptionEntityModel subscription = new SubscriptionEntityModel();
        subscription.subscriptionId = rs.getInt("subscription_id");
        subscription.name = rs.getString("name");
        subscription.emailAddress = rs.getString("email_address");
        subscription.phoneNumber = rs.getString("phone_number");
        subscription.organizationId = rs.getInt("organization_id");

        subscription.createdAt = new DateTime(rs.getTimestamp("created_at"));
        subscription.expiredAt = new DateTime(rs.getTimestamp("expired_at"));

        subscriptions.add(subscription);
    }

    sproc.close();
    db.destroy();

    return subscriptions;
}

最佳答案

查看结果集#wasNull

https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#wasNull()

Reports whether the last column read had a value of SQL NULL.

因此,您可以在 rs.getTimestamp() 之后使用它来检查读取的值是否为 SQL NULL,但请注意,如果是这种情况,ResultSet#getTimestamp 已经返回空引用。

https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getTimestamp(int)

the column value; if the value is SQL NULL, the value returned is null

您面临的问题是,当您将空引用传递给 DateTime 的构造函数时,它将被解释为现在

关于java - 如何判断 Java 中 Postgres 的时间戳是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44315844/

相关文章:

sql严格多于query

postgresql - 使用 on 与 Postgres 冲突时如何避免不必要的更新?

Java 客户端/服务器聊天室将消息作为对象发送

Java 最短成本路径 : Uninformed/Informed search from a (. txt) 文本文件

sql - 将Windows上的.sql文件导入到postgresql

sql - 如何在postgresql中获取不同组的第一个条目

java 日期格式 yyyy-mm-dd.hh.MM.ss.ms

java - Eclipse 和 SVN : Missing . 项目文件

java - JSP + Eclipse + TomCat : cannot be resolved to a type

sql - 如何高效查询带有标签的项目