简体   繁体   中英

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. 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. But when I execute the same query from Java JDBC client, the resultset contain entry which has ADDED_TIME equals to parameter1.

Here is the Java code of the client:

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 . It is only returned if I execute it using Java JDBC client. What could be the possible reason for this.

Appreciate any help on this,

The reason why the JDBC Java client gave different result is:

There are two data types that support date-time format in SQL Server:

  1. DATETIME
  2. DATETIME2

The data type of the column ADDED_TIME is DATETIME. But when setting the parameter using PreparedStatement.setTimestamp() the parameter implicitly gets mapped to DATETIME2 type. There seems to be no way to set it as DATETIME type when using setTimestamp() method. This is being discussed in [1] as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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