簡體   English   中英

在C#中的while循環內使用IF條件。 虛假值仍在循環

[英]Using IF condition inside a while loop in C#. False value still looping

我不知道為什么while循環中的else值仍然循環,無論結果是登錄還是無效。 警報對話框始終彈出。

這些是我的代碼。

MySqlConnection conn = new MySqlConnection();    
string query = "server=sample.com;port=3306;database=sample;user id=sample;password=sample";
conn.ConnectionString = query;

MySqlCommand cmd = new MySqlCommand("select * from wp_users", conn);
try
{
    conn.Open();


    MySqlDataReader myReader = cmd.ExecuteReader();

    string user1 = "";
    string pass1 = "";
    //bool stopLoop = false; // stop looping for false value;
    while (myReader.Read())
    {

        user1 = myReader[1].ToString(); //datacolumn -> user_login
        pass1 = myReader[2].ToString(); //datacolumn -> user_pass

        if ((user1 == txtUsername.Text) && (pass1 == txtPassword.Text))
        {

            Intent myIntent;
            myIntent = new Intent(Activity, typeof(index));

            string a = user1;

            myIntent.PutExtra("myItem", a);
            StartActivity(myIntent);
        }
        else
        {
            Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(Activity);
            alert.SetMessage("Invalid username or password");
            alert.SetPositiveButton("Ok", (senderAlert, args) =>
            {
                alert.Dispose();
            });
            alert.Show();
        }
    }
    myReader.Close();
}
catch (MySqlException ex)
{
    Android.Support.V7.App.AlertDialog.Builder except = new Android.Support.V7.App.AlertDialog.Builder(Activity);
    except.SetTitle("Please report this to our website(error server timeout)");
    except.SetMessage(ex.ToString());
    except.SetPositiveButton("Ok", (senderAlert, args) =>
    {
        except.Dispose();
    });
    except.Show();
}
finally
{
    conn.Close();
}

在您的問題中,您永遠不會說停止讀取數據或在找到所需記錄時使用中斷。

                MySqlDataReader myReader = cmd.ExecuteReader();

                string user1 = "";
                string pass1 = "";
                bool stopLoop = false;
                while (stopLoop == false && myReader.Read())
                {

                    user1 = myReader[1].ToString(); //datacolumn -> user_login
                    pass1 = myReader[2].ToString(); //datacolumn -> user_pass

                    if ((user1 == txtUsername.Text) && (pass1 == txtPassword.Text))
                    {
                        stopLoop = true;

                        //rest of the true if code

                        // If you didnt use a stopLoop flag you could have inserted here a break;
                    }
                    else
                    {
                        // your else code
                    }
                }
                myReader.Close();

您也可以查看我對問題評論的建議,以嘗試使其變得更好,因為我認為這不是必需的;-)

問題是您的邏輯略有缺陷,讓我來演示一下。 假設您有user1,user2,user3等,例如10。

你有

while reading through list
  if entered user = user item from list
     do happy stuff
  else 
     do unhappy stuff
end while.

所以我輸入user3

if user3 = user1 .. nope say unhappy stuff
if user3 = user2 .. nope say unhappy stuff
if user3 = user3 .. yes do happy stuff
if user4 = user3 .. nope say unhappy stuff
....

如果您有2000個用戶,那么1999年您將感到不快。

您需要一個像這樣的循環

item found = false
while reading through list
  if entered user = user from list
   item found = true
    do happy stuff
    break; // because theres no point checking another 1999 !
end while

if item found = false do unhappy stuff

與您的問題相關的代碼有2個問題。

首先,登錄成功后您就不會中斷循環。 使用break;可以輕松完成此操作break; 關鍵詞。

這樣您將獲得:

    [...]
    myIntent.PutExtra("myItem", a);
    StartActivity(myIntent);
    break;                               // <----
}
else [...]

第二個問題是,如果登錄不正確,則在每個循環中您還可以處理這種情況。 這意味着,如果數據與數據庫返回的第一個用戶的數據不匹配,則代碼將立即聲明登錄失敗。

您將需要跟蹤輸入是否與任何用戶匹配,並且僅當它與所有用戶都不匹配時(因此,在while循環之后),您才能處理失敗的登錄。


至於一些建議:

  • 如果這是實際用戶使用的應用程序,請不要將密碼以純文本格式存儲在數據庫中,不要對它們進行哈希處理並比較哈希值。 有關如何對密碼進行哈希處理,請參閱這篇文章
  • 無需從數據庫中獲取整個用戶表並在循環中檢查每個用戶,而是使用查詢立即檢查要查找的用戶。 數據庫針對搜索進行了優化,使您的編碼速度更快。

    就像是:

      using (var cmd = new MySqlCommand("select user_login from wp_users where user_login = @user and user_pass = @pass", conn)) { conn.Open(); // Set parameters cmd.Parameters.AddWithValue("@user", user); cmd.Parameters.AddWithValue("@pass", pass); // Get result using (var reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { // If ANY row, there is a user if (reader.Read()) { // Login succesfull } else { // Login failed } } } 

您應該在您的if使用String.Equals(user1 ,txtUsername.Text.ToString ())String.Equals(pass1 ,txtPassword.Text.ToString ())代替user1 == txtUsername.Textpass1 == txtPassword.Text 進行正確的字符串比較

您應該將else部分移出循環。 如果用戶名和密碼正確,則添加break; 作為if條件中的最后一條語句。

您可以維護一個布爾變量,假設isLogin=false; 登錄成功時,將此變量設置為true。 循環后,檢查標志並決定是否顯示登錄錯誤對話框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM