if-else语句不是while循环
问题描述:
内工作,我有,我想创建一个登录表单的问题,但else语句似乎被忽略。if-else语句不是while循环
如何编写此代码提取以便在将不正确的数据放入文本框时显示消息框? (所有数据库设置正确)。
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();
}
我试图把messagebox放在while循环之外,并且不能以所需的方式工作。 (下面的try方法是一个捕获,我没有包含它来节省空间)。
说了这么多,它似乎也只是选取数据库中的第一个用户。 任何线索或指导将不胜感激!
答
你不通过的结果需要循环,因为你只期望一行最大。我会做这种方式:
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
如果没有结果返回第一行的第一列,或空。
如果这是一个真正的项目,您需要使用SqlParameters
来避免SQL注入漏洞,并且还需要查看散列/ salting而不是存储纯文本密码。
+0
非常感谢,这个作品! – Glitchezz 2013-04-29 00:35:57
你应该真的* *使用参数化查询 - 你很容易受到这里的SQL注入。 – Blorgbeard 2013-04-29 00:07:47
感谢您的回复,但SQL注入不是我会关注的,因为这只是一个大学项目。 – Glitchezz 2013-04-29 00:08:59
不是说这是问题,但是你可以用一个简单的'else'替换你的else if(txt ...'。if if是多余的检查。 – MAV 2013-04-29 00:12:18