如何用字符串中的双撇号替换撇号?

Jam*_*123 7 c# sql

我有一个字符串

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

插入SQL表时会出错.所以我想用双撇号替换字符串中的撇号

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

如何在c#中操作它?

Oli*_*bes 10

很容易:

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

注意:使用命令参数通常更安全.特别是如果输入字符串的值不受代码控制(即用户条目).

  • 虽然这在技术上是正确的,但它会使原始提问者转向错误的方向.使用适当的参数并避免SQL注入漏洞要好得多. (4认同)

Pat*_*ins 10

使用Parameter对象.

  myCommand.InsertCommand.Parameters.Add("@myString", SqlDbType.VarChar, 200);
  myCommand.InsertCommand.Parameters["@myString"].Value = @"good overview of ESP's in more detail than you probably need.";
Run Code Online (Sandbox Code Playgroud)