Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

java - PSQLException: ResultSet not positioned properly, perhaps you need to call next

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;
}

I am using this code for authenticating a user. The username and password are extracted from the request parameter and passed onto this method for authentication. But it throws a:

org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.

Please advice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error is telling you exactly what's wrong - you're not calling next() on your ResultSet to get to the first row of the results.

This line:

if(rs!=null)

is pointless as far as I know; I don't believe executeQuery will ever return null. If there's a problem in your query, an exception will be thrown. If there are no results, it will return an empty result set. To see if there's a row, you should call next() and check the return value:

if (rs.next())

Additionally:

  • Catching an exception and just printing the stack trace without rethrowing is almost always the wrong approach
  • Your code suggests that you're storing passwords in plain text. Please don't. Really, really don't.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...