繁体   English   中英

在条件中使用NOW()查询在psql和JDBC中的行为不同

[英]Query with NOW() in criteria behaves differently in psql vs. JDBC

我正在通过控制台在psql中执行以下查询并获取输出:

select details
  from history_transactions
      ,history_operations
  where history_operations.transaction_id = history_transactions.id
    and type = 3
    and created_at >= NOW() - INTERVAL '5 minutes'

但是,当我从Java程序调用此代码时,它不返回任何输出。 ResultSetnull PFB我的代码:

Connection conn = getConnection();
java.sql.Statement stmt = null;
String sql ="select details from  history_transactions , history_operations where  history_operations.transaction_id=history_transactions.id and type =3  and  created_at >= NOW() - INTERVAL '5 minutes'";
try{
    stmt = conn.createStatement();
    rs = stmt.executeQuery(sql);
    while(rs.next()) {
        System.out.println("Inside resultset");
    }
}
catch(Exception e)
{
    e.printStackTrace();
}

知道我要去哪里错了吗?

我也没有任何例外。

注意:如果我将间隔从5分钟更改为6小时或更长时间,则它可以正常工作并提供输出。 如果我将间隔更改为<5小时,则结果集为空。 但是,如果我登录到psql服务器并按代码中的原样执行查询。 我正在输出。

我正在使用Java版本“ 1.8.0_151”和PostgreSQL JDBC 4.2驱动程序42.2.1-根据https://jdbc.postgresql.org/download.html-它是合适的驱动程序。

PostgreSQL NOW()函数返回timestamp with time zone值的timestamp with time zone 为了对timestamp类型的列使用该值(无时区),PostgreSQL需要隐式CAST该值以匹配该列类型。 但是,测试表明,如果将客户端和服务器设置为不同的时区,则通过psql连接与通过JDBC连接时,CAST的结果可能会有所不同。 例如:

服务器时区:UTC
客户时区:美国/丹佛,又称“ MST / MDT”,当前为UTC-7

通过psql连接时,

SELECT CAST(CAST(NOW() AS timestamp) AS varchar)

返回UTC值

2018-02-05 22:40:25.012933

但是当通过JDBC连接时,同一查询将返回MST值

2018-02-05 15:40:57.288587

要在JDBC下返回UTC值,我们可以执行

set time zone 'UTC'

在运行我们的SELECT查询之前。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM