2016-03-06 98 views
0

我創建一個簡單的登錄信息(用戶,密碼和功率水平; 1 - 普通用戶2,管理員)MySQL查詢登錄

所以,我的表只能有4列(ID,用戶名,密碼和lvl)。我已經有查詢輸入登錄,我想要的是創建一個「if」/條件來打開一個表單。例如,如果您輸入了您的信息,並且您是「Normal_user」表單顯示的普通用戶,但是如果您是管理員,則表單「Admin」會顯示。我的實際代碼沒有經過許可的級別是:

try 
     { 
      MySqlConnection c = new MySqlConnection("Server=localhost; database=SOIS; UID=root; Pwd=; "); 
      MySqlCommand cmd = new MySqlCommand("Select * from usuarios where empleado_id = '" + username.Text + "' and password = '" + password.Password + "'", c); 
       MySqlDataReader lectura; 
       c.Open(); 
       lectura = cmd.ExecuteReader(); 
       int count = 0; 
       while (lectura.Read()) { 
        count = count + 1; 
       } 
       if (count == 1) 
       { 
        MainWindow win2 = new MainWindow(); 
        win2.Show(); 
        c.Close();  //In this part I think can add another query and put it into an if 
        this.Close(); 
       } 
       else 
       { 
        c.Close(); 
       MessageBox.Show("Wrong information"); 
      } 

      c.Close(); 
     }catch(Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
+0

請注意,您的代碼非常容易受到[SQL注入](https://www.owasp.org/index.php/SQL_Injection)的威脅。請改用[參數化查詢](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx)!此外,你似乎以純文本存儲你的密碼是絕對不行的。請即使這只是一個用於學習目的的測試項目,請改變! – khlr

+1

感謝您的提示,我會調查並作出更改 –

回答

0

我假設您在數據庫中有第4列來標識管理用戶。

try 
     { 
      MySqlConnection c = new MySqlConnection("Server=localhost; database=SOIS; UID=root; Pwd=; "); 
      MySqlCommand cmd = new MySqlCommand("Select * from usuarios where empleado_id = '" + username.Text + "' and password = '" + password.Password + "'", c); 
       MySqlDataReader lectura; 
       c.Open(); 
       lectura = cmd.ExecuteReader(); 
       int count = 0; 
       bool isAdmin = false; 
       while (lectura.Read()) { 
        count = count + 1; 
        isAdmin = (lecture[3] == 1) ? true : false; 
       } 
       if (count == 1) 
       { 
        MainWindow win2 = new MainWindow(); 
        win2.Show(); 
        if(isAdmin) { 
         // if admin open admin form 
        } 
        c.Close();  //In this part I think can add another query and put it into an if 
        this.Close(); 
       } 
       else 
       { 
        c.Close(); 
       MessageBox.Show("Wrong information"); 
      } 

      c.Close(); 
     }catch(Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
+0

謝謝,只需要修改此行:isAdmin =(lectura [3] .Equals(1))?真假; –