[英]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.