I don't know why eclipse warn me "Dead Code" in this code of mine:
PreparedStatement p = conn.prepareStatement("SELECT name FROM user WHERE age = ? , city = ?");
p.setInt(1, (String) parameters.get("age"));
p.setString(2, (String) parameters.get("city"));
if (p == null) {
log.warn("User is not available");
return results;
}
the warning was in the log, can anybody tell me the reason of this? thank you.
p
can not be null
at that point, simply because you already called setInt
and setString
on p
and if it were null
there, then it would have thrown a NullPointerException
, thus never reaching your if
.
Also note that according to its documentation , preparedStatement
can't ever return null
. It can only return a valid statement or throw an exception. In the latter case your if
will also not be reached. That fact, however, is not checked by the compiler (because a broken implementation of prepareStatement
could theoretically return null
).
You need to do that null
check before you call any method on p
. If p is null
, it will never reach that line.
if p
is null
then in the second line itself there will be `NullPointerException' thrown.
change the code like below
PreparedStatement p = conn.prepareStatement("SELECT name FROM user WHERE age = ? , city = ?");
if(p != null){
p.setInt(1, (String) parameters.get("age"));
p.setString(2, (String) parameters.get("city"));
}else{
log.warn("User is not available");
return results;
}
or bring the if loop
before using p
PreparedStatement p = conn.prepareStatement("SELECT name FROM user WHERE age = ? , city = ?");
if (p == null) {
log.warn("User is not available");
return results;
}
p.setInt(1, (String) parameters.get("age"));
p.setString(2, (String) parameters.get("city"));
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.