Multiple Id's in In clause of SQL Query C# [closed]

妖精的绣舞 提交于 2019-11-26 14:57:00

问题


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?


回答1:


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();



回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!