I want to basically use multiple iD's in In clause of my sql query. Now i have two options one is to get the comma separated ID's from a textbox or i can put a list view or grid view to insert id's there and then get the id's to be used in sql statement. Can you please help me with the code, how to do this thing?
In order to get textbox value you have to code like this:-
"select * from table where id in ( "+textbox1.text+")";
But this will lead you to Sql Injection problem. So a better approach will be:-
var command = new SqlCommand("SELECT * FROM table WHERE id = @value")
{
Connection = connection();
};
command.Parameters.AddWithValue("value", textbox1.text);
var dataReader = command.ExecuteReader();
The correct way to send user input to the database is using parameters.
The IN
operator often confuses inexperienced developers since a lot of them try to use it with a single parameter that contains comma delimited values and expect it to return results. However that is a mistake since the IN
operator expect a list of values, not a single value containing a list.
So, to parameterize a query for the IN
operator what you need to do is break down the comma separated string in your code and provide the query with a parameter for each value.
Here is a basic example:
var userInput = "1,2,3,4,5,6";
var values = userInput.Split(',');
using(var command = new OdbcCommand())
{
var sql = "SELECT * FROM table where id IN(";
for(int i=0; i < values.Length; i++) {
sql = $"{sql} @{i},";
command.Parameters.Add($"@{i}", OdbcType.Int).Value = values[i];
}
command.CommandText = sql.TrimEnd(',') +");";
command.Connection = con;
using(var reader = Command.ExecuteReader())
{
while(reader.Read())
{
// do your stuff with the data
}
}
}
来源:https://stackoverflow.com/questions/46520435/multiple-ids-in-in-clause-of-sql-query-c-sharp