![](/img/trans.png)
[英]In string.Format escape user entered characters such as {0), {1}
[英]escape characters in SQL query string produced via string.format
我在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);
如果名字,姓氏等有撇號像O'Hare,O'Callahagan,則上述語句不會執行,因為更新語句的語法錯誤。
如何在string.format中轉義撇號?
如何在string.format中轉義撇號?
不要逃避它,而是使用參數化查詢。
想象一下,一個非常傳統的用戶名稱非常類似於SQL語句,用於刪除表或做同樣惡意的事情。 逃避報價不會有太大幫助。
請改用此查詢:
String sql = @"UPDATE Table
SET FIRST_NAME=@FirstName
, LAST_NAME=@LastName
, BIRTH_DATE=@BirthDate
WHERE CUSTOMER_NUMBER =@CustomerNumber";
之后,在相應的參數上設置FirstName
, LastName
, DateOfBirth
和Number
的值:
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);
您的RDMBS驅動程序將為您完成所有其他操作,保護您免受惡意攻擊。 作為一個額外的好處,當您的RDBMS的日期格式與您的計算機不同時,它可以讓您避免出現問題:由於您的date
將不再作為字符串表示傳遞,因此無需了解格式化日期的哪一部分代表一天,哪一個代表一個月。
您應該使用參數化查詢:
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
通過使用參數化查詢,您可以解決問題。 使用參數化查詢還有兩個優點:
使用參數化查詢。
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.