登录仅适用于数据库中的最后一个用户 [英] Login works only for last user in the database

查看:75
本文介绍了登录仅适用于数据库中的最后一个用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,该登录仅适用于数据库中的最后一个用户.我有一个while循环,但我认为它使程序转到了最后一个用户.我尝试使用if语句,但是只有第一个用户可以登录.

For some reason the login only works for the last user in the database. I have a while loop, but I think it makes the program to go to the last user. I tried using if statement but then only the first user can log in.

  if (username!=null && password!=null) {
    pagename = "main";
    } else {
    username = request.getParameter("username");
    password = request.getParameter("password");

            while(results.next()) 
            { 
            if(results.getString(2).equals(password) && results.getString(1).equals(username)) 
            { 
            pagename="main";
            } 
            else 
            { 
            pagename="start";
            } 
    }
  }

这是怎么引起的,我该如何解决?

How is this caused and how can I solve it?

推荐答案

您要将整个数据库表复制到Java的内存中,并在while循环中对所有记录进行比较.当与记录匹配时,您不会中止while循环,因此它将继续循环遍历其余记录,因此pagename每次都会被开始"覆盖.

You are copying the entire DB table into Java's memory and doing the comparison in a while loop over all records. You are not aborting the while loop when there's a match with a record, so it continues looping over the remaining records and so the pagename get overridden with "start" everytime.

您需要添加break语句:

if (results.getString(2).equals(password) && results.getString(1).equals(username)) { 
    pagename="main";
    break;
}

或者更好的方法是让SQL执行它专为设计的工作,选择并精确返回所需的数据:

Or, better, let SQL do the job it is designed for, selecting and returning exactly the data you need:

preparedStatement = connection.prepareStatement("SELECT id FROM user WHERE username=? AND password=MD5(?)");
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();

if (resultSet.next()) {
    pagename = "main";
}
else {
    pagename = "start";
}

这更加有效和明智.

这篇关于登录仅适用于数据库中的最后一个用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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