'else'的if / else在执行C#时不执行

时间:2012-03-12 09:25:47

标签: c# sql

我正在用C#设计一个ATM系统,对于登录功能,我使用SQL服务器数据库来比较输入的卡号和密码与数据库中的密码。当输入正确的卡号和密码时,一切正常,但是当输入的值不正确时,根本没有任何事情发生,我一直试图弄清楚它已经有一段时间了。有没有人对它可能有什么想法?甚至我的大学讲师都不知道!

//Select all fields from the table 'ATMCards' using the connection previously created and use the SqlDataReader to read the values

为了简化它我只是将messagebox.show放在else中,因为我想做的就是至少让它触发!

SqlCommand cmd = new SqlCommand("SELECT * FROM [ATMCards] WHERE (cardNumber = @cardNumber) AND (PIN = @PIN)", cn);
cmd.Parameters.AddWithValue("@cardNumber", cboxSimCard.Text);
cmd.Parameters.AddWithValue("@PIN", txtboxPIN.Text);

cmd.Connection = cn;
SqlDataReader r = null;
r = cmd.ExecuteReader();

//While the reader is in execution:
while (r.Read())
{
    //ADD IF NOT CONFISCATED DO THIS:
    if (((Boolean)(r["confiscated"]) == notConfiscated))
    {
        string cNum =  r["cardNumber"].ToString();
        string pin = r["PIN"].ToString();

        //Compare the results in the ATMCards table against those on the form used to log in
        if (string.Equals(cNum,cboxSimCard.Text) && string.Equals(pin,txtboxPIN.Text))
        {
            MessageBox.Show("Card number "+cNum+"  PIN "+pin); 
            //If the login details are correct then grant access to the menu screen by creating a new instance of it and hide the login form. Clear PIN to avoid the next user accessing the account
            MessageBox.Show("Open form all is good"); 
            txtboxPIN.Clear();
            Form myNewForm = new Menu();
            myNewForm.Show();
            this.Hide();
            break;
        }

        else
        {
            MessageBox.Show("Here"); 
        }

4 个答案:

答案 0 :(得分:8)

如果输入了错误的卡号和密码对,则不会从数据库返回任何行,因此while(r.Read())会立即返回false。

答案 1 :(得分:2)

当您的where条件不匹配时,返回的结果集没有行。第一个r.Read返回false,while循环的内容永远不会执行。

作为Henk Holterman注释,如果您调试代码,这将是显而易见的。

进一步简单回答......

你不应该像这样执行你的SQL。它会让你接受注射攻击。您可以使用Linq-To-Entities或在调用sp_ExecuteSQL时将SQL包装起来。

PIN不应存储为纯文本,而应存储为PIN和其他卡详细信息的安全散列。

卡号不应以纯文本格式存储。如果您永远不必阅读卡号,可以进行哈希处理。否则加密

我假设您在将查询传递到数据库之前使用模13或某些行业标准检查验证卡详细信息。

我并不是说你可以重新创建ATM内部实际发生的事情,但有些人对敏感数据所需的安全性点头肯定会产生额外的信用。 (双关语无意)

答案 2 :(得分:0)

你的代码是

  1. 不安全且可能注入
  2. 信用卡和信用卡必须加密且你没有
  3. 您的代码在故障情况下永远不会显示任何消息,因为如果没有数据被重新编入内部的if子句,而不会被执行
  4. 你可以使用

    if(reader.HasRows)
    ///then do happy case
    else
    //show error message
    

答案 3 :(得分:0)

对我来说似乎是这样:

if (string.Equals(cNum,cboxSimCard.Text) && string.Equals(pin,txtboxPIN.Text))

出错了。尝试使用与String.Equals(String, StringComparison)相同功能的重载。喜欢这个

if (cNum.Equals(cboxSimCard.Text, StringComparison.InvariantCultureIgnoreCase) &&   pin.Equals(txtboxPIN.Text, StringComparison.InvariantCultureIgnoreCase))