gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:00:35 25 4
gpt4 key购买 nike

我在尝试创建登录表单时遇到问题,但是 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方法后面是一个catch,为了节省篇幅我没有包含它)。

话虽如此,它似乎也只能获取数据库中的第一个用户。任何线索或指导将不胜感激!

最佳答案

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

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 注入(inject)漏洞,并且还要考虑散列/加盐而不是存储纯文本密码。

关于c# - If-Else 语句在 while 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16269412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com