Parameterized query ado.net issue(参数化查询 ado.net 问题)
问题描述
我正在使用此查询进行分页
I am using this query for pagination
string selectStatement = "SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY @sortMember @sortDirection ) AS RowNum, * FROM School) AS Rows WHERE RowNum > @pageFrom AND RowNum < @pageTo ";
command.Parameters.Add("@sortDirection", System.Data.SqlDbType.NVarChar, 50);
command.Parameters["@sortDirection"].Value = cmd.SortDescriptors.Count == 0 ? "" : cmd.SortDescriptors[0].SortDirection == System.ComponentModel.ListSortDirection.Ascending ? "" : "DESC";
如果 sortDirection 是 "" 我得到一个异常.如果你像这样使用它,它工作正常,但我想让它参数化查询.解决办法是什么?
if sortDirection is "" i get an exception. if u use it like this it works fine but i want to make it parameterized query. what is the solution?
string selectStatement = string.Format("SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY @sortMember {0} ) AS RowNum, * FROM School) AS Rows WHERE RowNum > @pageFrom AND RowNum < @pageTo ",System.ComponentModel.ListSortDirection.Ascending ? "" : "DESC);
我得到的例外是:'@sortDirection' 附近的语法不正确.
The exception i get is :Incorrect syntax near '@sortDirection'.
推荐答案
您不能参数化诸如表名、列、排序依据等内容.它们是强>查询.您需要将预期值列入白名单(以避免 SQL 注入)并将其直接连接到查询中(这是您的 string.Format 用法所做的).
You can't parameterise things like table-names, columns, order-by, etc. They are the query. You will need to white-list the expected values (to avoid SQL injection) and concatenate it into the query directly (which is what your string.Format usage does).
目前,order-by 位于变量的值上,每行都不会改变.本质上,排序(如所写)被忽略了.
At the moment, the order-by is on the vale of the variable, which doesn't change per-row. Essentially, the sort (as written) is ignored.
这篇关于参数化查询 ado.net 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:参数化查询 ado.net 问题
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
