Can we add a parameter to datatable.select in c #

I like to know if it is possible to add a parameter to datatable.select (expression). for instance

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

How to add this @Name parameter. I need to compare a value that contains a single quote, and in this case it did not work out.

Thanks in advance

+4
source share
2 answers

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

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

or if you want to use Like :

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

(note that a DataTable not vulnerable to SQL injection, since it is an object in memory)

+7
source

You can only pass an expression to the Select method.

If you need to pass the parameter dynamically, you can try this.

string Exp = "Name ='" + variable + "'";

 dt.select(Exp); 
-one
source

Source: https://habr.com/ru/post/1499817/


All Articles