Insert quote in mysql using c#

Can anyone help me to insert single quote in mysql using c#. I know how to achieve that, but i don't know the syntax, so far this is my code

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

but my txtcode doesnt get the value of \, and also i try this code

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

still not working.. anyone can guess how to achieve that? Thanks in advance

Jon Skeet
people
quotationmark

You don't need to perform any string replacements - just use parameterized SQL and it should be fine.

So you mustn't do this:

// BAD CODE - DO NOT USE
string sql = "INSERT INTO TABLE Person (ID, NAME) VALUES ('" + id 
    + "', '" + txtCode.Text + "')";

That is:

  • Vulnerable to SQL injection attacks (and awkward characters like quotes)
  • Brittle in the face of conversions (date/time conversions being particularly painful)
  • Hard to read, as it mixes the SQL and the data

Instead, you'd use something like:

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();
}

people

See more on this question at Stackoverflow