Entry
How do I escape quotes when building an SQL query?
Nov 11th, 2006 11:46
Matt Chatterley, manjay dwivedi, Nathan Wallace,
You can just do something like this:
// sqlQuery is your sql query string
// fieldValue is your string to write
sqlQuery = "update MyTable set field = '";
sqlQuery += fieldValue.Replace("'", "\\'");
sqlQuery += "'";
// fieldValue is now changed
Note however that this will change the value of fieldValue to have the
single quotes permanently escaped. If you want to leave fieldValue
intact then you can just make a copy of the string to change and
insert with.
// sqlQuery is your sql query string
// fieldValue is your string to write
sqlQuery = "update MyTable set field = '";
sqlQuery += String.Copy(fieldValue).Replace("'", "\\'");
sqlQuery += "'";
// fieldValue has not changed
//when u inserting the value from textfield of textarea
just use \(backslas) before '(quotes) then it's working fine
-----
OR
You can use stored procedures (with typed parameters) to perform your
query, and build an ADO.NET Command object (see a simple ADO.NET
tutorial for details on this, or look at the SqlCommand class). I
believe that if you take this approach (certainly true for MSSQL, not
sure about MySQL et al), ADO.NET will perform any relevant
escaping/safety-ensurance for you.