ADO.NET 是否会清理字符串 SqlParameters 中的通配符?

发布于 2024-10-20 03:03:50 字数 723 浏览 3 评论 0原文

ADO.NET 是否清理字符串类型 SqlParameters 中的通配符(即“%”或“_”)?另外,有必要吗?我已经尝试过谷歌搜索,但很难找到我想知道的内容。

例如,假设我有一个参数化查询:

string sql = "SELECT * FROM Users WHERE UserName LIKE @prefix";

SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("prefix", User.UserName);
//etc...

但用户以某种方式设法为自己获取像 % 这样的用户名。他的想法是他将看到所有用户,而不仅仅是他应该看到的用户。这是否有效,或者 % 会 a) 当值被参数化时被转义,或者 b) 由 SQL 服务器计算为文字 % 吗?

请注意,我意识到上述设计将是一个非常糟糕的设计。这只是一个虚构的例子。


编辑:我通过测试确认选项 b) 不会发生。

declare @prefix as varchar(10);
set @prefix = '%';
select * from MyTable where MyField like @prefix;
--returns everything

Does ADO.NET sanitize wildcards (i.e. "%" or "_") in string-type SqlParameters? Furthermore, does it need to? I've tried Googling for this, but it's hard to find exactly what I want to know.

For example, suppose I have a parameterized query:

string sql = "SELECT * FROM Users WHERE UserName LIKE @prefix";

SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("prefix", User.UserName);
//etc...

But the user somehow manages to get himself a username like %. His idea is that he'll see all users, not just the ones he was supposed to see. Will this work, or would the % get a) escaped when the value is parameterized, or b) evaluated as a literal % by the SQL server?

Note that I realize the above would be a really lousy design. It's just a made-up example.


Edit: I've confirmed by testing that option b) doesn't happen.

declare @prefix as varchar(10);
set @prefix = '%';
select * from MyTable where MyField like @prefix;
--returns everything

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放血 2024-10-27 03:03:50

不!没有什么需要清理的,它是有效值。您将其放入 LIKE 语句中是您的问题。 ADO.net 可防止 ' 和其他可能导致注入的字符。

No! There is nothing to sanitize, it is valid value. It is your problem that you put it into LIKE statement. ADO.net prevents ' and other chars that can cause injection.

感性不性感 2024-10-27 03:03:50

你需要自己逃避它,这样就可以了:

string sql = "SELECT * FROM Users WHERE UserName LIKE (@prefix + '%') ESCAPE '~'";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("prefix", User.UserName.Replace("~", "~~").Replace("%", "~%"));

You need to escape it yourself, this would do it:

string sql = "SELECT * FROM Users WHERE UserName LIKE (@prefix + '%') ESCAPE '~'";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("prefix", User.UserName.Replace("~", "~~").Replace("%", "~%"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文