如何在数据表列中搜索用户输入
目前我正在搜索如下。
DataRow[] 行 = dataTable.Select("FieldName='"+ 用户输入 + "'");
这里的问题是,每当用户提供带有单引号 (')
的输入时,它都会抛出错误。
我可以轻松地纠正它
DataRow[] 行 = dataTable.Select("FieldName='" + userInput.Replace("'","''") + "'");
我担心其他哪些用户输入可能会导致问题?
Currently I'm searching as below.
DataRow[] rows =
dataTable.Select("FieldName='"+
userInput + "'");
The problem here is whenever user provides an input with single quote (')
, it throws error.
I can easily correct it by
DataRow[] rows =
dataTable.Select("FieldName='" +
userInput.Replace("'","''") + "'");
I'm worried what other user inputs might cause problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里是尊敬的< a href="https://stackoverflow.com/users/22656/jon-skeet">先生。乔恩·斯基特。
Here is the exact answer from honourable Mr. Jon Skeet.
@Ismail:如果我们在前端查询或后端查询中使用用户输入之前验证用户输入,这将是一个好习惯。
所以我认为在你的场景中你必须具有像......这样的功能
,并且在验证中你可以进行任何检查。现在你只想检查'但将来,可能你将不得不检查其他东西。
根据您的需要,您可以检查验证函数的返回类型,如果您想修改输入数据,则修改并返回,否则只需返回 bool。
如果您想使用 DataTable.Select(filter) 进行数据过滤,那么您必须格式化/忽略或替换过滤语句中的特殊字符,为此您将不得不编写更多代码。如果你不想对特殊字符感到恐慌,那么你可以使用 LINQ 像
@Ismail: It would be a good habit if we validate user input before using that in front end query or in back-end query.
So i think in your scenario you must have function like...
and in validation you can do any check. right now you only want to check ' but in future, may be you will have to check some thing else.
and based on your need you can checge return type of validate function, if you want to modify input data then modify and return that else just return bool.
If you want to use DataTable.Select(filter) for data filter then you have to format/ignore or replace special character from filter statement and for that u will have to write more code. If you dont want to be panic for special character then you can use LINQ like
在这种情况下,我认为单引号是您唯一需要担心的字符,因为它用于分隔字符串值。有关表达式语法的详细信息,请参阅 DataColumn 的 MSDN 条目.Expression(创建过滤器表达式使用与 DataColumn.Expression 属性相同的规则)。
您无需指明您正在使用哪个版本的 C#,但使用 LINQ,您可以这样做:
一个权衡是,如果 DataTable 中有任何已删除的行,您还需要检查 RowState,但它确实提供了另一个选项。
In this case, I think the single quote is the only character you have to worry about since it is used to delimit string values. For more information on expression syntax, see the MSDN entry for DataColumn.Expression (creating a filter expression uses the same rules as for the DataColumn.Expression property).
You don't indicate which version of C# you are using, but with LINQ, you can do this:
One tradeoff is that you'll also need to check the RowState if you have any deleted rows in the DataTable, but it does provide another option.