本文介绍了使用参数使用 Like 运算符避免 SQL 查询中的 SQL 注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从我的前任那里接过一些代码,我发现了一个使用 Like 运算符的查询:
Taking over some code from my predecessor and I found a query that uses the Like operator:
SELECT * FROM suppliers WHERE supplier_name like '%'+name+%';试图避免 SQL 注入问题并将其参数化,但我不太确定这将如何实现.有什么建议吗?
Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?
注意,我需要一个经典 ADO.NET 的解决方案 - 我真的没有能力将这段代码切换到 LINQ 之类的东西.
note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.
推荐答案试试这个:
var query = "select * from foo where name like @searchterm"; using (var command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@searchterm", String.Format("%{0}%", searchTerm)); var result = command.ExecuteReader(); }框架会自动处理引用问题.
the framework will automatically deal with the quoting issues.
更多推荐
使用参数使用 Like 运算符避免 SQL 查询中的 SQL 注入?
发布评论