Java - preparedstatement

Ste*_*eve 2 java jdbc

ResultSet rs;

PreparedStatement st = MyConnection.prepareStatement("Select * from logindetails where Username = ? and Password = ?");

st.setString(1, username);
st.setString(2, password);

while (rs.next() )
{
    //login correct = true, redirect
}

rs.close();
MyConnection.close();
Run Code Online (Sandbox Code Playgroud)

这个问题是我不能使用PreparedStatement在while循环中使用next(),因为我想用用户输入的参数搜索数据库.

我怎样才能解决这个问题?

lim*_*imc 5

您不需要,while (rs.next())因为您PreparedStatement已使用您设置的用户名和密码查询了结果集.相反,使用if语句来测试结果集: -

// returns AuthenticatedUser object if authentication is successful, otherwise null
public AuthenticatedUser authenticate(String username, String password) {   
    PreparedStatement st = ...;
    st.setString(1, username);
    st.setString(2, password);

    ResultSet rs = st.executeQuery();

    AuthenticatedUser user = null;

    //login valid because there is something from the result set, then create user object
    if (rs.next() ) {
        // set all the useful user information in this POJO
        user = new AuthenticatedUser(username, rs.getString("name"), rs.getString("whatever_important_info"));
    }

    ... // close resultset, preparedStatement, connection, clean up, etc.

    return user;  
}
Run Code Online (Sandbox Code Playgroud)

从你的服务器/控制器,你可以做这样的事情来处理页面重定向: -

// call the method above to get the user object based on the provided username and password
AuthenticatedUser user = dao.authenticate(username, password);

// successful authentication
if (user != null) {
   // set user object in session so that you don't need to query the database for user info again and again
   session.setAttribute("user", user); 

   // redirect to welcome page
   request.getRequestDispatcher("/your-welcome-page").forward(request, response);
}
else {
   // redirect to login page if authentication fails
   request.getRequestDispatcher("/login-page").forward(request, response);
}
Run Code Online (Sandbox Code Playgroud)