使用参数使用 Like 运算符避免 SQL 查询中的 SQL 注入?

编程入门 行业动态 更新时间:2024-10-10 11:24:33
本文介绍了使用参数使用 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 注入?

本文发布于:2023-10-30 04:45:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541808.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   参数   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!