C# 通过string.format生成的SQL查询字符串中的转义字符
我用c#表示: 如果名字、姓氏等有O'Hare、O'Callahagan这样的撇号,则不会执行上述语句,因为update语句的语法错误 如何在string.format中转义撇号 如何在string.format中转义撇号 不要逃避它,而是使用参数化查询 设想一个用户使用与SQL语句极为相似的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
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
通过使用参数化查询,您可以解决问题。使用参数化查询还有两个其他优点:
- 防范
- 可读性
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