参数化查询 ado.net 问题

Parameterized query ado.net issue(参数化查询 ado.net 问题)
本文介绍了参数化查询 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 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)