在我的代码中,我需要当查询结果为空时,它应该返回false
。
我的代码:
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;
}
}
现在对于 userID
和 bookID
的给定值,我在 mysql 控制台中尝试并看到它的结果为空,但在我的代码中它返回 true
仍然!
为什么这里不是假的?
最佳答案
你需要检查语句的结果......
ResultSet rs= ps.execute();
rs.isBeforeFirst()
如果 ResultSet 中没有行,将返回 false
所以你的代码应该是这样的:
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;
}
关于java - JDBC结果为空时如何返回false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20053090/