使用executeQuery时出现NullPointerException
我的代码中有一个空指针异常
ResultSet rs = aStatement.executeQuery(Query); // it can't be executed
,如下所示:
public static boolean testLogin(String user, String password) throws SQLException {
String Query = "select * from TBL_Users where userName = '" + user + "' and passWord = '" + password + "' ";
ResultSet rs = aStatement.executeQuery(Query);
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true;
}
return false;
}
}
I have a null pointer exception in
ResultSet rs = aStatement.executeQuery(Query); // it can't be executed
my code is like this :
public static boolean testLogin(String user, String password) throws SQLException {
String Query = "select * from TBL_Users where userName = '" + user + "' and passWord = '" + password + "' ";
ResultSet rs = aStatement.executeQuery(Query);
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true;
}
return false;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
aStatement
很可能为 null。Most likely
aStatement
is null.听起来您认为 aStatement 不应该为 null,但事实确实如此。
这是糟糕的 JDBC 代码,原因有很多:
这是另一种编写方式。从接口开始:
编写实现:
Sounds like you think aStatement should not be null, but it is.
This is bad JDBC code, for many reasons:
Here's another way to write it. Start with an interface:
Write an implementation:
aStatement
变量显然为null
,请验证其设置是否正确。您应该考虑阅读 Java 命名约定 并确保使用较低的变量和 java bean 约定的驼峰式大小写。对于stackoverflow中的代码片段,如果它们不言自明,则应遵守SSCCE,这将帮助您获得更多更好的答案。您还应该提供发生异常的堆栈跟踪。
The
aStatement
variable is apparentlynull
, please validate that it is correctly set. You should consider read the Java Naming Conventions and make sure you use the lower camel case for variables and java bean conventions.For code snippets in stackoverflow if they are not self-explanatory, you should obey the rules of the SSCCE, this will help you to get more and better answers. Also you should provide a stack trace with the occured exception.
使用准备好的语句。
Use prepared statements.
info
指的是什么以及为什么在赋值之后立即有一个return
?What is
info
refering to and why is there areturn
imediatly after the assignments?