public UserBean authenticate(String username,String password){
PostGresDAO pg=new PostGresDAO(); //creates new connection
Connection conn=pg.getConnecion(); //return connection object
PreparedStatement ps;
ResultSet rs;
String query="select password,name from scg_users where username=?";
UserBean ub=null;
boolean authenticated=false;
try{
ps=conn.prepareStatement(query);
ps.setString(1, username);
rs=ps.executeQuery();
if(rs!=null){
authenticated=password.equals(rs.getString(1)); //exception raised here
if(authenticated){
ub=new UserBean();
ub.setUser(rs.getString(2));
ub.setUsername(username);
}
}
}
catch(SQLException e){
e.printStackTrace();
}
return ub;
}
我正在使用此代码对用户进行身份验证。用户名和密码从请求参数中提取并传递给此方法进行身份验证。但它抛出一个:
org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.
请指教。
最佳答案
错误告诉您确切出了什么问题 - 您没有在 ResultSet 上调用 next()
以获取结果的第一行。
这一行:
if(rs!=null)
据我所知毫无意义;我不相信 executeQuery
会返回 null。如果您的查询有问题,将抛出异常。如果没有结果,它将返回一个空结果集。要查看是否有一行,您应该调用 next()
并检查返回值:
if (rs.next())
另外:
- 捕获异常并只打印堆栈跟踪而不重新抛出是几乎总是错误的方法
- 您的代码表明您以明文形式存储密码。请不要。真的,真的不要。
关于java - PSQLException : ResultSet not positioned properly, 也许你需要接下来调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12103915/