2014-08-31 35 views
-2

昨天代碼工作正常。如果密碼錯誤,C#ELSE不會返回

使用bool readerRead的IS USERNAME EXIST仍然有效,並且使用有效的用戶名和密碼登錄成功仍然有效。

但錯誤的密碼驗證部分不起作用。如果我輸入了有效的用戶名,但輸入了錯誤的密碼,則代碼將轉到第一個if(bool)的ELSE並返回此用戶名dosnt exists消息。假設返回密碼不匹配否!!?

private void button_login_Click(object sender, EventArgs e) 
{ 
    // Retrieve the connection string from the settings file. 
    string conString = Properties.Settings.Default.mattDatabaseConnectionString; 

    // Open the same connection with the same connection string. 
    using (SqlCeConnection con = new SqlCeConnection(conString)) 
    { 
     con.Open(); 

     // Read in all values in the table. 
     using (SqlCeCommand query = new SqlCeCommand("SELECT * FROM customers WHERE (username = @usern AND password = @passwd)", con)) 
     { 
      //créé un paramètre pour passer la le string du textbox dans le SELECT -> WHERE 
      //utiliser ces parametres prévient le SQL-Injection 
      query.Parameters.Add("@usern", textBox_login_username.Text); 
      query.Parameters.Add("@passwd", CalculateMD5Hash(textBox_login_password.Text)); 
      //créé un int pour regarder si le row exist 

      SqlCeDataReader reader = query.ExecuteReader(); 

      //prend les numéros des columns 
      int columnUsername = reader.GetOrdinal("username"); 
      int columnPassword = reader.GetOrdinal("password"); 

      bool readerRead = reader.Read(); 

      //if username exist 
      if (readerRead) 
      { 
       while (readerRead) 
       { 
        string hash_pwd = CalculateMD5Hash(textBox_login_password.Text); 
        //if password match 
        if (hash_pwd == reader.GetString(columnPassword)) 
        { 
         MessageBox.Show("Welcome" + reader.GetString(columnUsername) + ". YourID is: " + reader["id"]); 
        } 
        //if password doesnt match 
        else 
        { 
         MessageBox.Show("Your password doesnt match"); 
         textBox_register_password.Clear(); 
        } 

        //remet le bool readerRead à false sinon le while loop à linfini car true. 
        //ou mettre break; 
        readerRead = false; 
       } 
      } 
      else 
      { 
       MessageBox.Show("This username dosnt exist"); 
      } 
     } 
    } 
} 

回答

1

對於錯誤的密碼,因爲您正在比較SQL查詢中的用戶名和密碼 - 沒有返回結果。

更改查詢

SELECT * FROM customers WHERE username = @usern 
+0

工作。是的,這是真的..我忘了我今天早上添加了'和密碼= @passwd',以確保選擇適當的行,如果有2行具有相同的用戶名。那麼我會用一種不同的方法。謝謝!! – MindKind 2014-08-31 16:14:03

+0

不僅如此,但錯誤的密碼邏輯永遠不會運行 - 如果密碼匹配,它也匹配第二次比較。 – 2014-08-31 16:54:15

+0

好的謝謝。 我解決了registring進程中的問題,使列名稱Unique = yes並嘗試捕獲。 更好的是這樣的。我的另一種方式是讓任何敏感..:D這是最好的學習方式! – MindKind 2014-08-31 20:34:15