开发者

Escape single quote in adhoc query

开发者 https://www.devze.com 2023-01-28 07:07 出处:网络
I have the following query: MySqlCommand command = new MySqlCommand( @\"SELECT `Customer ID`, `First Name`, `Last Name`, `Role`

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

精彩评论

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