简体   繁体   中英

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?

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.

You should use parameterized queries:

using (SqlCommand cmd = new SqlCommand("UPDATE Table SET FIRST_NAME= @FirstName, LAST_NAME= @LastName, BIRTH_DATE=@BirthDate where CUSTOMER_NUMBER = @CustomerNumber"))
{
    cmd.Parameters.Add(new SqlParameter("FirstName", FirstName));
    cmd.Parameters.Add(new SqlParameter("LastName", LastName));
    cmd.Parameters.Add(new SqlParameter("BirthDate", DateOfBirth));
    cmd.Parameters.Add(new SqlParameter("CustomerNumber", Number));

    // Now, update your database
} // the SqlCommand gets disposed, because you use the 'using' statement

By using parameterized queries, you solve your problem. Using parameterized queries has two other advantages:

Use parameterized query.

string commandString = "insert into MyTable values (@val1, @val2)";     
SqlCommand command = new SqlCommand(commandString, connection);
command.Parameters.AddWithValue("val1", "O'Hare");
command.Parameters.AddWithValue("val2", "O'Callahagan");
command.ExecuteNonQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM