2016-08-13 49 views
1

我想用c#登錄程序,用我的用戶名和密碼存儲到phpmyadmin中的SQL數據庫中。 這是我到目前爲止。在C#中選擇MySQL數據

private void button1_Click(object sender, EventArgs e) 
     { 
      MySqlConnection connection; 
      string server = "localhost"; 
      string database = "login"; 
      string uid = "root"; 
      string password = ""; 
      string connectionString; 
      connectionString = "SERVER=" + server + ";" + "DATABASE=" + 
      database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"; 


      connection = new MySqlConnection(connectionString); 

      try 
      { 
       connection.Open(); 
       if (connection.State == ConnectionState.Open) 
       { 
        connection.Close(); 
        Form1 frm = new Form1(this); 
        frm.Show(); 
        Hide(); 
       } 
       else 
       { 
        MessageBox.Show("Database Connection Failed", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("An Error Occured, Try again later.", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); 
      } 
     } 

它連接到數據庫,但我不希望它顯示form1直到輸入了有效的用戶名和密碼。 我猜我需要使用SELECT * FROM,但我不確定如何去做。

+0

的連接將失敗。 – user3185569

回答

4

You ca n使用這種方法,如果用戶名和密碼匹配

MySqlCommand cmd = dbConn.CreateCommand(); 
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = @username and [email protected]"; 
command.Parameters.Add("@username", txtUserName.Text); 
command.Parameters.Add("@password", txtPassword.Text); 
var count = cmd.ExecuteScalar(); 

if(count>0) 
    //Logged In 

只是說,如果你使用像

cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = '"+txtusernam +"'"; 

查詢時會開到SQL注入

警告

正如Steve在評論中提到的那樣明文中的密碼是同一個字符串級聯的漏洞

+0

只需在這裏添加警告。明文形式的密碼是字符串連接量相同的弱點。 – Steve

+0

@Steve謝謝。我會將它添加到我的回答中 –

+0

謝謝,密碼被散列。 – Lynnstrum

-2

下面的查詢使用

Select * from UsersTable Where Username='"+username+"' AND password='"+password+"' 

然後你就可以做一個,如果條件是,如果您的查詢包含一個結果(行),則用戶身份驗證(表存在)

注:選擇查詢可能獲取具有相同userName和 密碼的多個用戶,直到您保持用戶名在表中唯一

+1

請勿亂寫字串。 – Steve

+1

@Steve ok先生,接受,感謝您糾正我 –

+0

當然沒有什麼反對你。這個問題非常複雜,當我看到使用這種方法的答案時,我感覺非常糟糕。我無法刪除downvote現在,但你總是可以刪除答案或解決問題(但在這一點上你的答案將與另一個相同)。抱歉。 – Steve

0

你做嘗試,如果憑據是不正確的異常會被拋出,從而`趕上(異常前)`塊將執行這一

using(var con = new MysqlConnection{ ConnectionString = "your connection string " }) 
{ 
    using(var command = new MysqlCommand{ Connection = con }) 
    { 
     con.Open(); 

     command.CommandText = @"SELECT level FROM userTable WHERE [email protected], [email protected]"; 
     command.AddWithValue("@username", txtusername.Text); 
     command.AddWithValue("@password", txtpassword.Text); 

     var strLevel = myCommand.ExecuteScalar(); 

     if(strLevel == DBNULL.Value || strLevel == Null) 
     { 
      MessageBox.Show("Invalid username or password"); 
      return; 
     } 
     else 
     { 
      MessageBox.Show("Successfully login"); 
      hide(); // hide this form and show another form 
     } 

} 

}