1

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 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("%", "\\%")));

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I'll add that in but it feels like a hack. -edit- geeze, it doesnt even escape ". I cant use MySqlHelper.EscapeString at all. This isnt working
Try using a parametrized query. Then your query text will be ... LIKE CONCAT("%", @likeParm, "%"). You will then only have to apply the two Replace methods to the string to make it ready to be passed in as @likeParm.
Hmm, close. ok this works with .Replace("\\", "\\\\").Replace("_", "\\_").Replace("%", "\\%")) -edit- i cant +1 cause i undid it 45mins ago
Make sure you quote quotation marks too or you will be vulnerable to SQL injection. Using a parametrized query is really the best approach here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.