Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape characters in SQL query string produced via string.format

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?

like image 812
user1118468 Avatar asked Nov 30 '22 02:11

user1118468


1 Answers

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.

like image 155
Sergey Kalinichenko Avatar answered Dec 06 '22 16:12

Sergey Kalinichenko