2

I have a project where I call a MySQL query, which is built up from a string I send to the method.

I have a problem if the string has a single quote '

I want to replace it with a \' so it's safe for MySQL

But when I build up the query I add a single quote and a % in the beginning and the end of the string; for example '%texthere%'

So I need to know how do I replace every single quote except the first and last one?

So it will replace only from: '%thi'stext%'

To this: '%thi\'stext'%

4
  • 1
    This is really not too hard with an iterative solution based on .IndexOf(int, int). So what have you tried? Commented Mar 1, 2013 at 3:48
  • i cant figure out how to say string.replace("'", "\'") except the first and last one. or if that would cause an issue if there is no single quote except the '%texthere%' Commented Mar 1, 2013 at 3:49
  • 7
    You should use parameters. Commented Mar 1, 2013 at 3:50
  • @SLaks, but to what degree do you believe in your suggestion? ;) Commented Mar 1, 2013 at 3:51

6 Answers 6

4

Simple:

int first = s.IndexOf('\'');
int last = s.LastIndexOf('\'');
string prefix = s.Substring(0, first+1);
string query = s.Substring(first+1, last-first-1);
string suffix = s.Substring(last);
s = prefix + query.Replace("'", "\\'") + suffix;

Of course, you should really use SQL parameters instead.

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

Comments

1

so stupid me i finally looked over the method alot better

i fixed it by string.Replace("'", "\'")

BEFORE i add a % & ' the to the beginning and % & ' at the end

i learned alot from you guys, thanks so much

2 Comments

Heheh, this is the best solution. Next time, it is better to state your full question so that we can avoid this X-Y problem :)
"\'" is the same as "'": they have the value '. I think you want "\\'" or @"\'", which would have the value \'. (look up escape characters and verbatim strings to understand why)
0

First use a trim function to cut single quotes from each side of the string. Then replace "'" with "\'" and add the single quotes back to each side of the string. This would not work if ' was the first or last character in the string because it would be trimmed.

2 Comments

That will work with the OP's example. But it didn't seem clear to me that the quotes would always be the first and last characters.
how do i trim only the first and last single quote ? @KirkWoll i want to replace only the quotes in the middle of the text, as my sample from '%tes'there%' to '%tes\'there%'
0

The way I have done this before is as follows:

  1. Use IndexOf to get the index of the first occurrence of the character.
  2. Get a substring of the original string starting at the index found in Step 1
  3. Reverse the substring found in Step 2
  4. Repeat Step 1 on the reversed string from Step 3, and you are now left with a substring containing the string from after the first ' character to before the last one.
  5. Reverse the substring from Step 4 again (to get it back to original order) and replace the remaining ' characters with \'
  6. Rebuild the string using (pseudoCode) -

    finalString = string.Concat( originalString.Substring(0, firstIndex), replacedSubstringFromStep5, originalString.Substring(secondIndex, originalStringLength - 1)

This will get you a string with anything before and including the first ' character and anything after the last one from the original string, and everything in between will be the replaced ' characters that are now escaped for your MySQL query.

Hope this helps!

Edit: note when I did this, it was for string manipulation in an interlinking application, and not for database queries. I do agree it is better to use stored procs and parameters as others have stated; however, the solution I have provided, without getting into best practices and such, will do what OP is seeking.

8 Comments

seems that will help, but being i am not super expert, is there a example that will be helpful for me? or do you have your code how to do this ?
-1, that's what I call gratuitous overengineering. You really do not need to reverse the string twice just to replace a few characters.
Thanks for the down vote @nneonneo, why don't you suggest a better way to find the last ' character without reversing the string?
Also my answer assumes that the first and last character of the string is not automatically a ' character, meaning you have to preserve whatever comes before and after the required apostrophes in the SQL query
@Izzy G - I am on my iPad now but will try to post some actual code shortly.
|
0

I hope this method helps you: Assuming raw matches the pattern "'%free text here with single quotes%'"

    private string ReplaceSpecial(string raw)
    {
        return String.Format("'%{0}%'", raw.Substring(2, raw.Length - 2).Replace("'", "\\'"));
    }

Comments

0

Reffer bellow link

Strip double quotes from a string in .NET

Replace all double quotes withing String

Hope this one is help you if not get solution than tell me i will give another solution

EDIT Okey so try string like this and give feed back

string query=@"%thi'stext%";

1 Comment

but i dont want to replace the first or last ' i want to replace from '%thi'stext%' to this '%thi\'stext%'

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.