[Solved] How to pass a C# variable with apostrophe through MySql


The quick and dirty fix is to use something like:

level = level.Replace("'","whatever");

but there are still problems with that. It won’t catch other bad characters and it probably won’t even work for edge cases on the apostrophe.

The best solution is to not construct queries that way. Instead, learn how to use parameterised queries so that SQL injection attacks are impossible, and the parameters work no matter what you put in them (within reason, of course).

For example (off the top of my head so may need some debugging):

MySqlCommand cmd = new MySqlCommand(
    "insert into data (level, name) values (?lvl, ?nm)", con);
cmd.Parameters.Add(new MySqlParameter("lvl", level));
cmd.Parameters.Add(new MySqlParameter("nm", name)); 
cmd.ExecuteNonQuery();

5

solved How to pass a C# variable with apostrophe through MySql