Friday, October 5, 2012

How do i escape single qoute (') in MySQL using c#

How do i escape single qoute (') in MySQL using c#

if you want to insert a data with a single qoue (') like the example below:

INSERT INTO tblname (`Field1`) VALUES ('5'4');

then you need to escape the single qoute (') using backslash (\), the correct SQL would be,


INSERT INTO tblname (`Field1`) VALUES ('5\'4');

to do that in c# assuming 5'4 is inside a textbox name txtheight, then the code will look like this,

 INSERT INTO tblname (`Field1`) VALUES ('" + txtheight.Text.Replace("'","\'") + "');

or

String.Format("INSERT INTO tbl (`Name`) VALUES ('{0}')", txtheight.Text.Replace("'","\'"))

0 comments: