C# 使用c在mysql中插入引号#

C# 使用c在mysql中插入引号#,c#,mysql,C#,Mysql,有人能帮我用c#在mysql中插入单引号吗。我知道如何实现,但我不知道语法,到目前为止这是我的代码 if (txtcode.Text.Contains("'") == true) { txtcode.Text.Replace("'", "\'"); } 但是我的txtcode没有得到\的值,我也尝试了这段代码 if (txtcode.Text.Contains("'") == true) { txtcode.Text.Replace("'", "\\'"

有人能帮我用c#在mysql中插入单引号吗。我知道如何实现,但我不知道语法,到目前为止这是我的代码

 if (txtcode.Text.Contains("'") == true)
  {
      txtcode.Text.Replace("'", "\'");
  }
但是我的txtcode没有得到\的值,我也尝试了这段代码

 if (txtcode.Text.Contains("'") == true)
  {
      txtcode.Text.Replace("'", "\\'");
  }

仍然不工作。。任何人都能猜到如何做到这一点?提前感谢

您应该真正使用参数化查询,它将正确处理引号,如下所示:

string s = "Text with this \'quote\'";

MySqlCommand cmd = new MySqlCommand("INSERT INTO table (Column) VALUES (@quotedString);", connection);
cmd.Parameters.AddWithValue("@quotedString", s);
cmd.ExecuteNonQuery();
这也防止了SQL注入的进行。

您不需要执行任何字符串替换-只要使用参数化SQL就可以了

所以你不能这样做:

即:

  • 易受攻击(和引号等笨拙字符)
  • 面对转换时很脆弱(日期/时间转换特别痛苦)
  • 很难读取,因为它混合了SQL和数据
相反,您可以使用以下内容:

string sql = "INSERT INTO TABLE Person (ID, NAME) VALUES (@id, @name)";
using (var command = new MySqlCommand(sql, conn))
{
    command.Parameters.Add("@id", MySqlDbType.VarChar).Value = id;
    command.Parameters.Add("@name", MySqlDbType.VarChar).Value = txtCode.Text;
    command.ExecuteNonQuery();
}
你能试试这个吗

if (txtcode.Text.Contains("'") == true)
  {
      txtcode.Text.Replace("'", @"\\'");
  }

同样,用这种方式保护报价也不是一个好主意。你可以用Jon Skeet或Thorsten Dittmas的答案。。。
if (txtcode.Text.Contains("'") == true)
  {
      txtcode.Text.Replace("'", @"\\'");
  }