How do i escape mysql strings in C# for use with LIKE
I want to find a word in my list of tags. They can be at the beginning, end or middle so i tried writing.
Where name like "%@0%"
That didnt work so i tried
@"LIKE ""%" + MySql.Data.MySqlClient.MySqlHelper.EscapeString(q) +@"%"
I thought that worked so i tried searching %. The results showed up all my tags, i expected only tags with % in them (so that would be none ATM).
How do i escape strings properly? and use it to search the middle of text?
-edit-
The solution开发者_如何学JAVA is the below. I ran it against a few test and it passed them all. The query is
... where n.name LIKE CONCAT("%", @some_name , "%") ...;
then in code
cmd.Parameters.AddWithValue("@some_name", val.Replace("\\", "\\\\").Replace("_", "\\_").Replace("%", "\\%")));
You also need to escape %
and _
characters in the string, since those are special wildcards used by the LIKE
operator:
@"LIKE ""%" +
MySql.Data.MySqlClient.MySqlHelper.EscapeString(q)
.Replace("_", "\\_").Replace("%", "\\%") +
@"%"
You might consider wrapping this in a static method for reusability.
精彩评论