2010-12-05 85 views
0

我有以下查詢:逃生的即席查詢單引號

MySqlCommand command = new MySqlCommand(
@"SELECT `Customer ID`, `First Name`, `Last Name`, `Role` 
    FROM `Contacts` WHERE `Customer ID` = '" + customerID + "'", connection); 

如果客戶ID具有內撇號(即Adam's Meat),我得到的錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Meat'' at line 1

是什麼使這個查詢工作的最好方法是什麼?

+0

我沒有獲得足夠的創建存儲過程 – Peter 2010-12-05 23:59:40

回答

2

你應該用參數來代替,這樣還可以防止SQL注入:

MySqlCommand command = new MySqlCommand(@"SELECT `Customer ID`, `First Name`, `Last Name`, `Role` FROM `Contacts` WHERE `Customer ID` = ?CostumerID", connection); 
command.Parameters.Add("?CustomerID", customerID);