Using an 'IN' operator with a SQL Command Object and C# 2.0

后端 未结 3 826
离开以前
离开以前 2021-01-19 05:15

I would like to call a sql statement such as:

Select * From Table Where Column in (\'value1\', \'value2\', \'value3\')

Is it as simple as s

3条回答
  •  死守一世寂寞
    2021-01-19 05:30

    @Charles: You're going into the right direction, but we're using parametrized queries to mainly prevent SQL injections. Putting 'external' values (params string[] args) hardcoded in queries is asking for trouble. You can iterate the arguments, but you still have to use parameters like this:

       string[] values = new [] {"value1", "value2", "value3", "value4"};
       StringBuilder query = new StringBuilder("Select * From Table Where Column in (");
       SqlCommand cmd = new SqlCommand();
       cmd.Connection = new SqlConnection("Your connection string");
       for(int i = 0; i < columns.Length; i++)
       {
           string arg = string.Format("@arg{0}", i);
           cmd.Parameters.AddwithValue(arg, SanatizeSqlString(columns[i]));
           sb.AppendFormat("{0}, ", arg);
       }
       sb = sb.Remove(sb.Length -2, 2);
       sb.Append(")");
       cmd.CommandText = sb.ToString();
    

    This way you'll end up with a query like:

    select * from table where column in (@arg0, @arg1, @arg2, @arg3)
    

提交回复
热议问题