How can I check a string for incorrect MySQL syntax caused by (') ?
for example: We Bike'd fast
I need to get rid of the ' before inserting it into the Database.
How can I check a string for incorrect MySQL syntax caused by (') ?
for example: We Bike'd fast
I need to get rid of the ' before inserting it into the Database.
You should use MysqlCommand
and command paramters to build your insert statement, this will do the escaping for you.
Alternatively there is a EscapeString
method you can use.
The simple answer is:
textValue = textValue.Replace("'","''");
But it is usually better to use command parameters.
See SqlCommand.Parameters Property on msdn. (I do not know the MySql equivalent)
EDIT:
Example with Replace:
string sql = String.Format("SELECT * FROM tbl WHERE name ='{0}'",
textBox1.Value.Replace("'","''"));
You can add the using System.Web
directive to your .cs file and use the HTMLEncode
which will then replace '
with &apos
but when you read it back out you'll have to call HTMLDecode()
to convert it back to '
.
This you would use before you create your parametrized statement on the front end. Then pass the end result as a parameter to your sqlCommand.