Skip to Main Content

Java Database Connectivity (JDBC)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

PreparedStatement setNull(...) in SQL WHERE clause

843854Jul 23 2004 — edited Nov 20 2014
Hi All,

I'm trying to do something like this
   PreparedStatement pstmt = con.prepareStatement("SELECT * FROM users WHERE firstname=? AND middlename=?");
   pstmt.setString(1, firstname);
   if (middlename != null) {
       pstmt.setString(2, middlename);
   }
   else {
       pstmt.setNull(2, Types.VARCHAR);
   }
   ResultSet resultSet = pstmt.executeQuery();
Despite I know some records will match the query when middlename == null, resultSet is always fetching no records. I know that the problem is about using setNull(...) method for parameteres in the WHERE clause since it probably is replacing the question mark by "null" but it should remove the previous equal sign and append " IS NULL" instead.

I have searched on this phorum for a while but all threads have led me to a dead end. Since most of them are from 2000 to 2002 I'm wondering if someone knows now a good solution for this issue without having to prepare 2 different SQL sentences, which sometimes won't be practical at all.

Thanks in advance.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 4 2010
Added on Jul 23 2004
22 comments
1,247 views