简体   繁体   中英

Boolean method is returning true everytime

I'm using SQL to compare a date of an event

public static boolean sameDate(String DateString)
{

   PreparedStatement statement = Application.database.newStatement("SELECT * FROM BookShift WHERE id = ?  IN (SELECT id FROM Class WHERE Date  = ?)"); 

    try 
    {
       if(statement !=null)
       {
           statement.setInt(1, main.id);
           statement.setString(2, DateTwo);

           ResultSet results = Application.database.runQuery(statement);

           if (results != null)
           {
               return true;
           }
           else {
            return false;
            }
        }
    }
    catch (SQLException resultsexception)
   {
        System.out.println("Database result processing error: " + resultsexception.getMessage());
    }
    return false;
   }

Whenever I run my program and try booking a new shift, regardless of whether it does clash or not it always returns that it does.

You need to check if the result set has any rows or not, not check if it is null.

 if (results.next())
 {
     return true;
 }
 else {
     return false;
 }

or, of course, just

return results.next();

As the comments say, it is not generally correct to check if results is null. I don't have the SQL experience to tell you what runQuery() will return on a query that fails, but I doubt that it's null, I would expect it to return an empty ResultSet .

Checking if it's null first isn't a bad thing, and in fact is a good idea to avoid NullPointerException throws. However, it's not enough to just use that check.

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