[英]Same query provides different results in SQL Server client and JDBC client
I'm using SQL Server in my project and I am trying to retrieve entries in a table between two timestamps.我在我的项目中使用 SQL 服务器,我正在尝试检索两个时间戳之间的表中的条目。 The schema of the table is given below:
该表的架构如下所示:
CREATE TABLE ENTRY (
ID INTEGER IDENTITY(1,1) NOT NULL,
NAME VARCHAR (2000),
USER_ID VARCHAR (31) NOT NULL,
ADDED_TIME DATETIME NOT NULL
);
I need to get the entries that are added after a particular timestamp and the current timestamp.我需要获取在特定时间戳和当前时间戳之后添加的条目。 For this I have tried the below mentioned query:
为此,我尝试了下面提到的查询:
SELECT * FROM ENTRY WHERE
ADDED_TIME>$parameter1 AND ADDED_TIME<$currentTime ORDER BY ADDED_TIME DESC
SELECT * FROM ENTRY WHERE
ADDED_TIME>'12/03/2020 12:13:08.583' AND ADDED_TIME<'12/03/2020 13:36:05.159' ORDER BY ADDED_TIME DESC
When executing this query directly on the SQL client, I got all the expected results.当直接在 SQL 客户端上执行此查询时,我得到了所有预期的结果。 But when I execute the same query from Java JDBC client, the
resultset
contain entry which has ADDED_TIME equals to parameter1.但是当我从 Java JDBC 客户端执行相同的查询时,
resultset
集中包含 ADDED_TIME 等于参数 1 的条目。
Here is the Java code of the client:这是客户端的Java代码:
String sql = "SELECT * FROM ENTRY WHERE ADDED_TIME>? AND ADDED_TIME<? ORDER BY ADDED_TIME DESC";
Date to = new Date();
PreparedStatement statement = conn.prepareStatement(sql);
statement.setTimestamp(1, new Timestamp(Long.parseLong("1606977788583")));
statement.setTimestamp(2, new Timestamp(to.getTime()));
ResultSet results = statement.executeQuery();
The resultset contain entry that has ADDED_TIME
as 1606977788583
.结果集包含
ADDED_TIME
为1606977788583
的条目。 It is only returned if I execute it using Java JDBC client.只有当我使用 Java JDBC 客户端执行它时才会返回它。 What could be the possible reason for this.
这可能是什么原因。
Appreciate any help on this,感谢您对此的任何帮助,
The reason why the JDBC Java client gave different result is: JDBC Java客户端给出不同结果的原因是:
There are two data types that support date-time format in SQL Server: SQL Server中有两种数据类型支持日期时间格式:
The data type of the column ADDED_TIME
is DATETIME. ADDED_TIME
列的数据类型是 DATETIME。 But when setting the parameter using PreparedStatement.setTimestamp()
the parameter implicitly gets mapped to DATETIME2 type.但是当使用
PreparedStatement.setTimestamp()
设置参数时,参数会隐式映射到DATETIME2类型。 There seems to be no way to set it as DATETIME type when using setTimestamp()
method.使用
setTimestamp()
方法时,似乎无法将其设置为DATETIME类型。 This is being discussed in [1] as well.这也在 [1] 中进行了讨论。
Fixed it by correcting the query as follows:通过更正查询来修复它,如下所示:
String sql = "SELECT * FROM ENTRY WHERE
ADDED_TIME> CONVERT(DATETIME, ?) AND
ADDED_TIME< CONVERT(DATETIME, ?)
ORDER BY ADDED_TIME DESC";
[1] https://github.com/microsoft/mssql-jdbc/issues/443 [1] https://github.com/microsoft/mssql-jdbc/issues/443
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.