2017-04-15 68 views
-1

我使用短小精悍庫的東西是錯在這裏我似乎無法使其工作,即使密碼或用戶名錯了,它開闢了新的形式,使一個登錄表單C#小巧玲瓏如何知道查詢是正確的

if (string.IsNullOrEmpty(txtUsername.Text)) 
     { 
      MessageBox.Show("Please enter your usernmae.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      txtUsername.Focus(); 
      return; 
     } 
     try 
     { 
      using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString)) 
      { 
       var data = db.Query("select Username,Password from UserLog", commandType: CommandType.Text); 
       if ((data.SingleOrDefault() !=null) 
       { 
        MessageBox.Show("You have been succesfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); 
        FormHome frm= new FormHome(); 
        frm.ShowDialog(); 
        this.Close(); 
       } 

       else 
       { 
        MessageBox.Show("Your Username or Password is Incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); 
       } 
      } 

     } 
     catch(Exception ex) 
     { 
      MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 
+0

看看數據內容,爲什麼' data.SingleOrDefault()!= null'始終爲真。 – Vladimir

回答

2

你只是發送此查詢數據庫,以便將每次不管返回結果的登錄信息的:

select Username, Password from UserLog 

所以當然它會通過,因爲你不過濾記錄。只要你在數據庫中有一條記錄,它就會通過。

您需要發送的用戶登錄信息,並檢查記錄,根據您正試圖驗證當前用戶的登錄信息存在:

IEnumerable users = db 
    .Query("select Username, Password from UserLog where UserName = @UserName and Password = @Password", 
    new {UserName = txtUsername.Text, Password = // put the password here}); 
if (users.Any()) 
{ 
    // authenticated so do whatever 
}