2017-05-08 34 views
0

在我的應用程序中,我有一個登錄系統。這是基本的,所以我不需要任何加密。問題是,當我想登錄時,我插入憑據(用戶名和密碼),但它沒有任何東西。我的代碼是:C# - 無法從數據庫獲得價值

public void iniciarsessaobutton_Click(object sender, EventArgs e) 
{ 
    string txtuser = textusername.Text; 
    string txtpass = textlogin.Text;  

    MySqlCommand cmd = new MySqlCommand("SELECT password FROM empregados WHERE user='" + txtuser + "';", mConn); 
    mConn.Open();   
    MySqlDataReader login = cmd.ExecuteReader();    
    login.Read();    
    string getpass = login["password"].ToString(); 

    if (getpass == txtpass) 
    {     
     mConn.Close(); 
     MessageBox.Show("Sessão iniciada"); 
     Admin adm = new Admin(); 
     this.Hide(); 
     adm.Show(); 
    } 
    else 
    { 
     mConn.Close(); 
     MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente."); 
    }    
} 
+1

「mConn」變量是否在任何地方初始化? – gaganshera

+0

您是否嘗試使用調試程序逐句通過您的代碼?我很確定它確實有* *但顯然不是你期望它做的。 – Filburt

+1

您的代碼易受SQL注入攻擊,通常不安全。密碼不應以純文本形式存儲在數據庫中。 –

回答

0

我想提出一些修改意見中提到的一些改進以及一些一般性改進。請參閱我在代碼中解決的問題:

public void iniciarsessaobutton_Click(object sender, EventArgs e) 
{ 
    string txtuser = textusername.Text; 
    string txtpass = textlogin.Text; 

    // Put your connection into a using() block 
    using (MySqlConnection conn = new MySqlConnection(variableWithYourConnectionStringHere)) 
    { 
     // Put your commend into a using() block 
     // enclose your column names in backticks to avoid conflict with MySql reserved keywords 
     // add a placeholder (@username) for your parameter 
     // use LIMIT 1 if you only expect 1 row matching your condition 
     using(MySqlCommand cmd = new MySqlCommand("SELECT `password` FROM empregados WHERE `user` = @username LIMIT 1", conn)) 
     { 
      mConn.Open(); 

      // add a parameter with your TextBox value 
      cmd.Parameters.AddWithValue("@username", txtuser); 

      // If you only retrieve 1 value, use ExecuteScalar to return only 1 value 
      // cast the returned object as string 
      string getpass = cmd.ExecuteScalar() as string; 

      if (getpass == txtpass) 
      { 
       MessageBox.Show("Sessão iniciada"); 
       Admin adm = new Admin(); 
       this.Hide(); 
       adm.Show(); 
      } 
      else 
      { 
       MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente."); 
      } 
     } 
    } 
} 
+0

我試着說你說蝙蝠繼續不工作@Filbort。以下是我的代碼:(https://drive.google.com/open?id=0B0UsguTsdfErS1FsdHl0ckRSOWM) –