How to replace an apostrophe with a double apostrophe in a string?

I have a line

good overview of ESP in more detail than you probably need .

When pasted into an SQL table, it gives an error. So I want to replace the apostrophe in the string with a double apostrophe, for example

good overview of ESP' in more detail than you probably need

How to do it in C #?

+7
source share
5 answers

Very simple:

 string s = "good overview of ESP in more detail than you probably need."; string escaped = s.Replace("'","''"); 

Note. It is generally safer to use command options. Especially if the values โ€‹โ€‹of the input strings are not controlled by your code (i.e. user records).

+10
source

Use the Parameter object.

  myCommand.InsertCommand.Parameters.Add("@myString", SqlDbType.VarChar, 200); myCommand.InsertCommand.Parameters["@myString"].Value = @"good overview of ESP in more detail than you probably need."; 
+8
source

I have been working on this issue for a long time. Do this on the client by replacing one quotation mark with two single quotation marks. This works if you execute sp with multiple varchar input parameters. The only problem with this is SQL injection, that is, people can see what you are doing on the client, which is never good. The only way around this is to use SQL options on the server, as they said earlier.

+2
source

String.Replace(String,String) should work fine. In this example you need:

 String.Replace("'", "''") 

However, I do not think this will fix your problem. I think you are more suitably looking for:

 String.Replace("'", "\'") 

The reason for this is that MySQL, and I would have imagined other versions of SQL, expected rows to be enclosed in single quotes.

0
source

myCommand.InsertCommand.Parameters.Add ("@myString", SqlDbType.VarChar, 200); myCommand.InsertCommand.Parameters ["@ tuZbttd"]. Value

0
source

All Articles