Java-PreparedStatement [英] Java - preparedstatement

查看:78
本文介绍了Java-PreparedStatement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();

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

The problem with this is I cannot use the next() in the while loop using the PreparedStatement, because I want to search the database with the parameters input by the user.

我该如何解决?

推荐答案

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

You don't need while (rs.next()) because your PreparedStatement has already queried the result set using the username and password you set. Instead, use if statement to test the result set:-

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

在服务器/控制器中,您可以执行以下操作来处理页面重定向:-

From your servet/controller, you can do something like this to handle the page redirection:-

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

这篇关于Java-PreparedStatement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆