PSQLException:ResultSet未正确定位,也许您需要调用next

Mon*_*oon 5 java postgresql postgresql-9.1

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;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用此代码来验证用户身份.用户名和密码从请求参数中提取并传递给此方法进行身份验证.但它抛出一个:

org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.
Run Code Online (Sandbox Code Playgroud)

请指教.

Jon*_*eet 16

错误告诉您到底出了什么问题 - 您没有调用next()ResultSet来到达结果的第一行.

这一行:

if(rs!=null)
Run Code Online (Sandbox Code Playgroud)

据我所知,毫无意义; 我不相信executeQuery会永远返回null.如果查询中存在问题,则会引发异常.如果没有结果,则返回空结果集.要查看是否有一行,您应该调用next()并检查返回值:

if (rs.next())
Run Code Online (Sandbox Code Playgroud)

另外:

  • 捕获异常并仅打印堆栈跟踪而不重新抛出几乎总是错误的方法
  • 您的代码表明您以纯文本格式存储密码.请不要.真的,真的没有.