C# 通过string.format生成的SQL查询字符串中的转义字符

C# 通过string.format生成的SQL查询字符串中的转义字符,c#,sql,string,formatting,C#,Sql,String,Formatting,我用c#表示: 如果名字、姓氏等有O'Hare、O'Callahagan这样的撇号,则不会执行上述语句,因为update语句的语法错误 如何在string.format中转义撇号 如何在string.format中转义撇号 不要逃避它,而是使用参数化查询 设想一个用户使用与SQL语句极为相似的SQL语句删除表或执行同样恶意的操作。转义引号不会有多大帮助 请改用此查询: String sql = @"UPDATE Table SET FIRST_NAME=@FirstName , LA

我用c#表示:

如果名字、姓氏等有O'Hare、O'Callahagan这样的撇号,则不会执行上述语句,因为update语句的语法错误

如何在string.format中转义撇号

如何在string.format中转义撇号

不要逃避它,而是使用参数化查询

设想一个用户使用与SQL语句极为相似的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的日期格式与计算机不同时出现的问题:因为
日期
不再作为字符串表示形式传递,因此理解格式化日期的哪一部分表示一天不会有问题,哪个代表一个月。

使用参数化查询

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();

应使用参数化查询:

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
通过使用参数化查询,您可以解决问题。使用参数化查询还有两个其他优点:

  • 防范
  • 可读性

使用参数化SQL!尝试下一步:我使用参数更改了程序的整个结构。谢谢:)@user1118468不客气!如果这对你有用,请考虑通过点击旁边的灰色复选标记来接受答案。这会让站点的其他访问者知道,您不再积极寻找改进的解决方案,并为您赢得一个全新的堆栈溢出徽章。如果我改用SqlDataAdapter呢?我想知道的是:当遇到像“Robert”这样的恶意名称时,转义引号为什么没有多大帮助?;DROP TABLE Students;--”? 我认为将单引号转义为2个单引号时没有问题。由于转义,恶意删除表将是字符串,因此不会执行。
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