我想调用一个sql语句,例如:
Select * From Table Where Column in ('value1', 'value2', 'value3')
是否像设置命令参数的值等于" ('value1', 'value2', 'value3')
" 一样简单?
@Charles:你正朝着正确的方向前进,但我们正在使用参数化查询来主要防止SQL注入.params string[] args
在查询中硬编码"外部"值()会遇到麻烦.您可以迭代参数,但仍然必须使用如下参数:
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();
这样您最终会得到如下查询:
select * from table where column in (@arg0, @arg1, @arg2, @arg3)