开发者

Escape single quote in adhoc query

I have the following query:

MySqlCommand command = new MySqlCommand(
@"SELECT `Customer ID`, `First Name`, `Last Name`, `Role` 
  FROM `Contacts` WHERE `Customer ID` = '" + custome开发者_Python百科rID + "'", connection);

If a customer ID has an apostrophe within, (i.e. Adam's Meat), I get the error:

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

What is the best way to make this query work?


You should use Parameters instead, this way you also prevent SQL Injection:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜