2011-02-22 43 views
2

MySQL查詢爲什麼慣於此命令正確執行:執行從asp.net

using (MySqlCommand myCommand = new MySqlCommand("Update jobs SET poster_email = '@1', url = '@2' WHERE company = '@3'; ", myConn)) 
    { 
     myCommand.Parameters.AddWithValue("@1", email); 
     myCommand.Parameters.AddWithValue("@2", url); 
     myCommand.Parameters.AddWithValue("@3", company); 
     myConn.Open(); 
     myCommand.ExecuteNonQuery(); 
    } 

但當我代替@ 3與實際值它的工作原理:

using (MySqlCommand myCommand = new MySqlCommand("Update jobs SET poster_email = '@1', url = '@2' WHERE company = 'MyCompany'; ", myConn)) 
{ 
    myCommand.Parameters.AddWithValue("@1", email); 
    myCommand.Parameters.AddWithValue("@2", url); 

    myConn.Open(); 
    myCommand.ExecuteNonQuery(); 
} 

的值傳遞在公司變量與第二個示例中硬編碼的值相同。我已經加入了調試器,以確保公司變量被添加爲參數,並且它是我期望的值。即。沒有空格和修剪()

任何想法我做錯了什麼?

更新:「?」

這也適用,但我擔心SQL注入......

string myQuery = string.Format("Update jobs SET poster_email = '{0}', url = '{1}' WHERE company = '{2}'; ", email, url, company); 

    using (MySqlCommand myCommand = new MySqlCommand(myQuery, myConn)) 
    { 
     myConn.Open(); 
     myCommand.ExecuteNonQuery(); 
    } 

回答

1

我相信你想使用的MySQL命令一而不是一個 「@」:

using (MySqlCommand myCommand = new MySqlCommand("Update jobs SET poster_email = '?1', url = '?2' WHERE company = '?3'; ", myConn)) 
{ 
    myCommand.Parameters.AddWithValue("?1", email); 
    myCommand.Parameters.AddWithValue("?2", url); 
    myCommand.Parameters.AddWithValue("?3", company); 
    myConn.Open(); 
    myCommand.ExecuteNonQuery(); 
} 

http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html#connector-net-examples-mysqlcommand-parameters

+0

我給它一個嘗試,它沒有什麼區別... – Pedro