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
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:
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();
}
See more on this question at Stackoverflow