2013-05-21 85 views
-1

這裏就是我試圖使用EMAILID檢索用戶名的密碼。無法執行cmd.ExecuteReader()

string query="select name from userdetails where emailid=" + email + ";" ; 
connection.Open(); 
MySqlCommand cmd = new MySqlCommand(query,connection); 
MySqlDataReader rd = cmd.ExecuteReader(); 
while(rd.Read()) 
{ 
    uname = (string)rd["emailid"]; 
    return uname; 
} 
+0

什麼是'email'的典型值,它從何而來? 「無法執行」是什麼意思?它不編譯?它編譯但引發異常?什麼是例外? –

回答

2

把你emailin事務所qoute因爲它是VARCHAR這樣的..

string query="select name from userdetails where emailid='" + email + "';" ; 

但是,這可能會導致SQL注入......所以用這個...

string query="select name from userdetails where [email protected];" ; 
MySqlCommand cmd = new MySqlCommand(query,connection); 
cmd.Parameters.AddWithValue("@email",email); 
1

更新您的select這樣的詢問在單引號中加入email

string query = "select name from userdetails where emailid='" + email +"';"; 

或 您可以使用參數化查詢是這樣的:

string query="select name from userdetails where [email protected]" ; 
MySqlCommand cmd = new MySqlCommand(query,connection); 
cmd.Parameters.AddWithValue("@email", email); 
3

參數值從SQL Injection

string query="select name from userdetails where [email protected]" ; 
MySqlCommand cmd = new MySqlCommand(query,connection); 
cmd.Parameters.AddWithValue("@email", email); 

避免試試這個代碼片段:

string connStr = "connection string here"; 
string sqlStatement = "select name from userdetails where [email protected]"; 
using (MySqlConnection conn = new MySqlConnection(connStr)) 
{ 
    using(MySqlCommand comm = new MySqlCommand()) 
    { 
     comm.Connection = conn; 
     comm.CommandText = sqlStatement; 
     comm.CommandType = CommandType.Text; 

     comm.Parameters.AddWithValue("@email", email); 

     try 
     { 
      conn.Open(); 
      MySqlDataReader rd = cmd.ExecuteReader(); 
      // other codes 
     } 
     catch(SqlException e) 
     { 
      // do something with the exception 
      // do not hide it 
      // e.Message.ToString() 
     } 
    } 
} 

爲了正確編碼

  • 使用using語句正確的對象處理
  • 使用try-catch塊妥善處理異常
+0

對於字符串,使用添加(),而不是AddWithValue! http://stackoverflow.com/questions/9155004/difference-with-parameters-add-and-parameters-addwithvalue –

+0

@FabianBigler感謝提醒我的問題當時的情況。我用'AddWithValue()'正常情況下':)' –

+1

哈哈,我沒有看到誰是你問。有趣的coindicence。 –