c#
  • mysql
  • 2012-12-09 120 views 0 likes 
    0

    我有一些問題,我看到互聯網上代碼的和平只有這個與Oledb完成。數據庫連接C#ExecuteNonReader與MySql

    我現在有rewrited爲MySQL.data.mysqlclient代碼如下:

    MySqlDataReader dr = null; 
         MySqlCommand cmd = null; 
         string cmdstr = "SELECT * FROM users WHERE email='"+UsrName.Text+"' and password='"+PassWrd.Text+"' LIMIT 1"; 
         dr = cmd.ExecuteNonReader(); 
         cmd = new MySqlCommand(cmdstr, connection); 
         cmd.Dispose(); 
    
         if (dr.Read() == true) 
         { 
          MessageBox.Show("Succesvol ingelogd"); 
         } 
         else 
         { 
          MessageBox.Show("Geen juiste gegevens"); 
         } 
         connection.Close(); 
    
        } 
    

    現在的問題是爲dr = cmd.ExecuteNonReader()另一種方法。

    UPDATE ----------------

    string server; 
         string database; 
         string uid; 
         string password; 
         server = "localhost"; 
         database = "cmstt"; 
         uid = "root"; 
         password = ""; 
         string connectionString; 
         connectionString = "SERVER=" + server + ";" + "DATABASE=" + 
         database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"; 
    
         MySqlConnection connection = new MySqlConnection(connectionString); 
    
         connection.Open(); 
    
         MySqlDataReader dr = null; 
         MySqlCommand cmd = null; 
         string cmdstr = "SELECT * FROM users WHERE email='"+UsrName.Text+"' and pass='"+PassWrd.Text+"' LIMIT 1"; 
         dr = cmd.ExecuteReader(); 
         cmd = new MySqlCommand(cmdstr, connection); 
    
    
         if (dr.Read() == true) 
         { 
          MessageBox.Show("Succesvol ingelogd"); 
         } 
         else 
         { 
          MessageBox.Show("Geen juiste gegevens"); 
         } 
         cmd.Dispose(); 
         connection.Close(); 
    
    +1

    您的代碼清楚地向SQL注入開放。請使用參數化的SQL,例如'cmd.Parameters.Add(「@ email」,email);' –

    +0

    哦,是的,小鮑比桌子。 http://imgs.xkcd.com/comics/exploits_of_a_mom.png – Pacane

    回答

    0

    你過早處置CMD。在關閉連接之前處理它。

    +0

    連接處於打開狀態,cmd在連接關閉前被廢止。 仍然有錯誤 –

    2

    這將是ExecuteReader()ExecuteNonReader()

    //這裏提到您的連接和連接字符串。

     connection.open() 
    
         SqlDataReader dr = null; 
         MySqlCommand cmd = null; 
         string cmdstr = "SELECT * FROM users WHERE email='"+UsrName.Text+"' and password='"+PassWrd.Text+"' LIMIT 1"; 
    
         cmd = new MySqlCommand(cmdstr, connection); 
         dr = cmd.ExecuteReader(); 
    
         if (dr.Read() == true) 
         { 
          MessageBox.Show("Succesvol ingelogd"); 
         } 
         else 
         { 
          MessageBox.Show("Geen juiste gegevens"); 
         } 
         connection.Close(); 
    
        } 
    
    +0

    dr = cmd.ExecuteReader(); nullReferenceException未處理: 未將對象引用設置爲對象的實例。 –

    +0

    確保你已經打開了sql server的連接。 – Moiz

    相關問題