I have the statement in c# :
String sql = String.Format("UPDATE Table SET FIRST_NAME='{0}',LAST_NAME='{1}',BIRTH_DATE='{2}' where CUSTOMER_NUMBER ='{3}'",FirstName, LastName,DateOfBirth,Number);
The above statement doesn't execute if the first name,last name etc have apostrophe like O'Hare,O'Callahagan because of this the update statement gets the wrong syntax.
How to escape the apostrophe in string.format?
How to escape the apostrophe in string.format?
Don't escape it, use parameterized query instead.
Imagine a user with a really unconventional name strongly resembling SQL statements for dropping a table or doing something equally malicious. Escaping quotes is not going to be of much help.
Use this query instead:
String sql = @"UPDATE Table
SET FIRST_NAME=@FirstName
, LAST_NAME=@LastName
, BIRTH_DATE=@BirthDate
WHERE CUSTOMER_NUMBER =@CustomerNumber";
After that, set values of FirstName
, LastName
, DateOfBirth
, and Number
on the corresponding parameters:
SqlCommand command = new SqlCommand(sql, conn);
command.Parameters.AddWithValue("@FirstName", FirstName);
command.Parameters.AddWithValue("@LastName", LastName);
command.Parameters.AddWithValue("@BirthDate", BirthDate);
command.Parameters.AddWithValue("@CustomerNumber", CustomerNumber);
Your RDMBS driver will do everything else for you, protecting you from malicious exploits. As an added benefit, it would let you avoid issues when the date format of your RDBMS is different from your computer: since your date
would no longer be passed as a string representation, there would be no issues understanding which part of the formatted date represents a day, and which one represents a month.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With