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(),因为我想用用户输入的参数搜索数据库。
我该如何解决这个问题?
答案 0 :(得分: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;
}
从你的服务器/控制器,你可以做这样的事情来处理页面重定向: -
// 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);
}
答案 1 :(得分:2)
不确定我是否正确理解了您的问题,但我猜您想要遍历结果集并访问列数据......
rs = st.executeQuery();
while (rs.next() ) {
rs.getString("columnname");
}
答案 2 :(得分:0)
如果这是用于生产应用程序(而不是学习或家庭作业),为什么不使用像iBatis这样的抽象层来隔离这个生物传感器呢?