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

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 09:54:34

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