In my code, i need when the result of query is empty, it should return false
.
My code:
public boolean user_bookValidationQuery(String userID, String bookID) {
Connection con;
PreparedStatement ps;
String query = " select * from borrowed where userID=? and bookID=? ";
try {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query);
ps.setString(1, userID);
ps.setString(2, bookID);
if (ps.execute()) {
System.out.println("You can do it! , id DB");
return true;
} else return false;
} catch (SQLException sqle) {
sqle.printStackTrace();
return false;
}
}
Now for a give value for userID
and bookID
, i try in mysql console and see that it's result was empty, But in my code it return true
still!
Why not false here?
you need to check the result of the statement ...
ResultSet rs= ps.execute();
rs.isBeforeFirst()
will returns false if there are no rows in the ResultSet
so your code should look like this :
try {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query);
ps.setString(1, userID);
ps.setString(2, bookID);
ResultSet rs= ps.execute();
if (!rs.isBeforeFirst() ) {
System.out.println("empty");
return false;
}else {
System.out.println("with data");
return true;
}
} catch (SQLException sqle) {
sqle.printStackTrace();
return false;
}