Can we add parameter in datatable.select in c# - c#

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);
How to add this parameter #Name. I need to compare a value which contains single quote and it gets failed in the above case.
Thanks in advance

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);
or, if you want to use Like:
string query = string.Format("Name LIKE '%{0}%'", name.Replace(#"'", "''"));
(note that a DataTable is not vulnerable to sql-injection since it's an in-memory object)

You can pass only expression to Select method.
In case if you need to pass the parameter dynamically then you can try this.
string Exp = "Name ='" + variable + "'";
dt.select(Exp);

Related

Passing in Oracle Parameter to SQL string

I'm having a problem where I don't know how I'm supposed to pass in an Oracle parameter where the C# type is a string and the Oracle type is a Varchar2.
Currently I'm passing in this string as CMS','ABC thinking that Oracle will add in the '' that surround this string making it a varchar2 that looks like 'CMS','ABC'.
This works for a single string like CMS but when the value is something longer, like something typically in a IN (list) command the parameter won't be passed in correctly.
This is the code I'm referring too.
string sql = 'SELECT name FROM Pers p WHERE p.FirstName IN (:names)';
The below works when the value of :names being passed in is CML without any quotes.
OracleParameter param = new OracleParameter(":names", OracleDbType.Varchar2, "CML", ParameterDirection.Input);
Below doesn't work when the value of :names being passed in is CML','ABC with quotes on the inside.
OracleParameter param = new OracleParameter(":names", OracleDbType.Varchar2, "CML','ABC", ParameterDirection.Input);
Why is that?
Does Oracle add in single quotes around the parameter when it's passed into the sql statement? Why doesn't it add quotes around the second case?
ODP.NET parameters do not work with multiple, comma separated values. Each parameter is treated as a single value, whatever kind of quotes it contains.
Oracle does not add quotes around parameter values when passed to a query. Quotes are just a way to write a VARCHAR value in a query, but when using parameters, Oracle doesn't "replace your parameter with its value then execute the query", as this would allow SQL injection.
If that was the case, imagine your parameter value was: "CML', 'ABC');DROP DATABASE Test;--". Oracle would then execute SELECT name FROM Pers p WHERE p.FirstName IN ('CML', 'ABC');DROP DATABASE Test;--'!
See this question for ideas on how to solve your problem: Oracle Parameters with IN statement?
From your comments/answers I was able to come up with this solution. I hope it helps others who come.
To get around ODT.NET parameters not working with multiple comma separated values you can divide each value into its own parameter. Like the following.
string allParams = "CML, ABC, DEF";
string formattedParams = allParams.Replace(" ", string.Empty); // Or a custom format
string [] splitParams = formattedParams.Split(',');
List<OracleParamter> parameters = new List<OracleParameter>();
string sql = #"SELECT * FROM FooTable WHERE FooValue IN (";
for(int i = 0; i < splitParams.Length; i++)
{
sql += #":FooParam" + i + ",";
parameters.Add(new OracleParameter(":FooParam" + i, OracleDbType.Varchar2, splitParams[i], ParameterDirection.Input));
{
sql = sql.Substring(0, (sql.Length - 1));
sql += ')';
The string sql will now have this as it's value: SELECT * FROM FooTable WHERE FooValue IN (:FooParam0,:fooParam1, etc...)
This will solve the problem.
Another approach would be to add in a bunch of OR clauses for each parameter. The above example is better since you don't write a bunch of OR clauses though.

intersystem cache C# query with name like?

I am trying to use like in a Cache sql query such as:
select * from person where name like ?.
I am passing the parameter like below.
CacheParameter param = new CachemParameter("NAME", CacheDBType.NVarChar);
param.Value = tbxName.Text.ToUpper();
command.parameters.Add(param);
Then I execute the reader.
The results is nothing.
I know in MSSQL I use name like 'Lawson%'. How do I do this in a Cache query?
TIA
Mike
According to the doc example
Your command could use %STARTSWITH instead of like:
select * from person where name %STARTSWITH ?
I finally figured out that all I had to do was to concatenate the "%" to the parameter being passed and it worked such as:
param.Value = tbxName.Text.ToUpper() + "%";

datatable .net 2.0 select with double single quote returns no results

I've datatable as follows
DataTable ex= new DataTable();
ex.Columns.Add("Object");
ex.Columns.Add("Found");
ex.Rows.Add("vase''s","True");
string keyword="vase''s";
DataRow [] drs = ex.Select("[Object] like '%" + keyword + "%'");
drs is always empty I've tried with equal I've the same results and I've tested in other frameworks I've the same also
what's wrong in my select statement ?!
Update
I realized that it's due to single quote is considered as one in the query statement but how can I do that search in a generic way
Modify your code to be like below
DataTable ex = new DataTable();
ex.Columns.Add("Object");
ex.Columns.Add("Found");
ex.Rows.Add("vase's", "True"); //don't escape here
string keyword = "vase''s";
//Use a equal to comparison rather than using LIKE operator
DataRow[] drs = ex.Select("[Object] = '" + keyword + "'");
The string value in your table literally has two single quotes. You do not escape single quotes in C# strings. The Select statement just needs two single quotes to tell the parser that the quote is not the end of the constant string value. So either keep a single quote in the value:
ex.Rows.Add("vase's", "True");
or search for a string with two single quotes:
string keyword = "vase''''s";
When you added that DataRow, you're informed the vase''s value (with two single quotes) and you (probably) don't want it.
However you MUST escape it in the query, like below:
DataTable ex = new DataTable();
ex.Columns.Add("Object");
ex.Columns.Add("Found");
ex.Rows.Add("vase's", "True");
foreach (DataRow row in ex.Rows)
Console.WriteLine(row["Object"]); // "vase's"
string keyword = "vase's";
DataRow[] drs = ex.Select("[Object] like '%" + keyword.Replace("'", "''") + "%'");
Console.WriteLine("{0} rows found", drs.Length);

How can I use a defined string constant in DataTable.Select() method?

I am using the Select command to select particular data rows from a DataTable:
DataRow[] dr;
dr = dataTable.Select("Roll_No = '"+rNo+"'");
I am getting the correct answer, but what if I want to use a constant defined for Roll_No?
I have defined constants:
public const string ROLL_NUMBER = "Roll_No";
So what will be the code for DataTable.Select()?
If I'm understanding your correctly, just substitute the variable for the hard-coded value.
var rows = dataTable.Select(string.Format("{0} = '{1}'", ROLL_NUMBER, rNo));
Assuming Roll_No is a numeric field, those single parentheses in the Select statement might mess up your query... if you don't get the expected results, try removing them.
Alternatively, you've also got the option of using a LINQ statement:
var rows = dataTable.AsEnumerable()
.Where(x => x.Field<int>(ROLL_NUMBER) == rNo);
Update (from follow-up comment):
can I use like follows? var dr = datTable.Select("Constants.ROLL_NUMBER = '"+rNo+"'"); here , Constants.ROLL_NUMBER is constant defined for roll number.
No, because your variable name is inside of a quote and so you'll end up filtering on the string literal "ROLL_NUMBER", not the underlying column name stored in ROLL_NUMBER.
To use your code, you'd do it like this:
var dr = dataTable.Select(Constants.ROLL_NUMBER = "'" + rNo + "'");
A string is a string. You already know how to concatenate strings because you're already doing it. ROLL_NUMBER would just be another string, just like rNo in your current code.
That said, I would tend to use String.Format for that sort of expression.
dataTable.Select() Method can only pass strings. Just Like it
public DataRow[] Select(string filterExpression,string sort)
If You want to pass a constant than you have to convert it into string.

Select statement with where clause in C#

How to write a select statement with where clause.i need to compare with a string value.
I tried this:
string get_dropdown_value = dropdown_category.SelectedItem.Value;
...but it gives me this error:
Invalid column name 'get_dropdown_value'.
You will have to show the select statement you are using. I suspect you have done something like this:
string selectStatement = "SELECT * FROM SOME_TABLE WHERE SOME_COLUMN = get_dropdown_value";
While it should be like:
string selectStatement = "SELECT * FROM SOME_TABLE WHERE SOME_COLUMN = " + get_dropdown_value;
Edit: As others mentioned, this is prone to SQL Injection. So, you might want to use SqlParamter (assuming you are using SQL).
Try this code
insted of
string get_dropdown_value = dropdown_category.SelectedItem.Value;
Put
string get_dropdown_value = dropdown_category.SelectedItem.Text;

Categories