我们可以在datatable.select中添加参数吗? [英] Can we add parameter in datatable.select in c#

查看:222
本文介绍了我们可以在datatable.select中添加参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在datatable.select(表达式)中添加参数。例如

I like to know is it possible to add parameter in datatable.select(expression).For example

string query="Name=@Name";          
//dt is comming from database.
dt.Select(query);

如何添加此参数 @Name 。我需要比较一个包含单引号的值,在上述情况下它会失败。

How to add this parameter @Name. I need to compare a value which contains single quote and it gets failed in the above case.

预先感谢

推荐答案

您可以使用 String.Format ,您需要使用两个转义单引号:

You can use String.Format, you need to escape single quotes with two:

string query = string.Format("Name='{0}'", name.Replace(@"'", "''"));
var rows = dt.Select(query);

或者,如果您想使用 Like

or, if you want to use Like:

string query = string.Format("Name LIKE '%{0}%'", name.Replace(@"'", "''"));

(请注意, DataTable 不容易受到攻击sql-injection,因为它是一个内存对象)

(note that a DataTable is not vulnerable to sql-injection since it's an in-memory object)

这篇关于我们可以在datatable.select中添加参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆