If-Else语句在while循环中不起作用

本文关键字:不起作用 循环 while 语句 If-Else | 更新日期: 2023-09-27 18:11:28

我有一个问题,我试图创建一个登录表单,但是else语句似乎被忽略了。

我如何编写此代码提取,以便在将不正确的数据放入文本框时显示消息框?(所有数据库设置正确)。

try
{
    sc.Open();
    SqlDataReader myReader = null;
    SqlCommand myCommand = new SqlCommand("select * from StudentRecords where ID = '" + txtBoxUsername.Text + "' ", sc); //where ID = '" + txtBoxUsername.Text + "' and DOB = '" + textBoxPassword.Text + "'
    myReader = myCommand.ExecuteReader();
    while (myReader.Read())
    {
        if (txtBoxUsername.Text == (myReader["ID"].ToString()) && textBoxPassword.Text == (myReader["DOB"].ToString()))
        {
            LoginSuccessForm loginfrm = new LoginSuccessForm();
            loginfrm.Show();
            this.Hide();
        }
        else if (txtBoxUsername.Text != (myReader["ID"].ToString()) || textBoxPassword.Text != (myReader["DOB"].ToString()))
        {
            MessageBox.Show("Incorrect Password and/or Username", "Error");
            break;
        }
    }
    sc.Close();
}

我已经试过把消息框放在while循环之外,这并没有以期望的方式工作。(try方法后面有一个陷阱,为了节省空间,我没有包括它)。

也就是说,它似乎也只拾取数据库中的第一个用户。任何线索或指导将不胜感激!

If-Else语句在while循环中不起作用

您不需要遍历结果,因为您只期望最多一行。我将这样做:

using (var cmd = sc.CreateCommand()) {
   cmd.CommandText = "select 1 from Students where Username=.. and Password= ..";
   if (cmd.ExecuteScalar() != null) {
      // username and password matched a user
   }
   else {
      // no match 
   }
}

ExecuteScalar返回第一行的第一列,如果没有结果则返回null。

如果这是一个真实的项目,您需要使用SqlParameters来避免SQL注入漏洞,并且还要考虑散列/盐化而不是存储纯文本密码。