简体   繁体   中英

Preparedstatement date check is null

I need to make query like this

SELECT * FROM tanks WHERE (creationDate >= ? or ? is null) and (creationDate >= ? or ? is null)

Then I've set

stmt.setObject(1, fromDate);
stmt.setObject(2, fromDate);
stmt.setObject(3, toDate);
stmt.setObject(4, toDate);

but I can't execute a query cause I've got an exception that Java cannot determine type of parameter $2 (sorry, I don't know why but all exception are in Russian).

When I get rid of ? is null everything works fine.

Does anybody have ideas how to deal with it?

Your query should be

SELECT * FROM tanks WHERE (creationDate >= ? or creationDate is null) and (creationDate >= ? or creationDate is null)

And you should only set two parameters corresponding to two ?

Not sure of anything that will allow you to use "? is Null" but you can do it in an alternative way something like this:

 if(fromDate!=null && toDate!=null){
      statement = connection.prepareStatement("SELECT * FROM tanks WHERE creationDate >= ? and creationDate >= ?");
      statement.setDate(1,fromDate);
      statement.setDate(2,toDate);

      ResultSet rs = statement.executeQuery();
 } else if(fromDate==null && toDate==null) {
      statement = connection.prepareStatement("SELECT * FROM tanks");
      ResultSet rs = statement.executeQuery();
 } else {
      statement = connection.prepareStatement("SELECT * FROM tanks WHERE creationDate >= ? ");
      statement.setDate(1,fromDate!=null?fromDate:toDate);

      ResultSet rs = statement.executeQuery();
 } 

Hope this helps.

Based on this thread , it seems this is a PostgreSQL JDBC driver bug that was introduced with protocol version 3.

The workarounds suggested in the thred are to degrade the protocol

jdbc:postgresql://host:port/database?protocolVersion=2

or to explicitly cast the arguments

SELECT ?::timestamp IS NULL
SELECT CAST(? AS timestamp) IS NULL

I was experiencing this same problem and was able to resolve it using the explicit cast.

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