虽然我不同意“重复问题”的选定答案(或许多棘手的答案),但这里有一个答案,它显示了一种与我的以下建议非常相似的方法。
(我已投票决定将这个问题作为重复问题结束,因为有这样的答案,即使被埋没了。)
只有一个SQL 值可以绑定到任何给定的占位符。
虽然有办法将所有数据作为“一个值”发送,但我建议动态创建占位符:它简单、干净,并且在大多数情况下都能可靠地工作。
考虑一下:
ICollection<string> resources = GetResources();
if (!resources.Any()) {
// "[Resource No_] IN ()" doesn't make sense
throw new Exception("Whoops, have to use different query!");
}
// If there is 1 resource, the result would be "@res0" ..
// If there were 3 resources, the result would be "@res0,@res1,@res2" .. etc
var resourceParams = string.Join(",",
resources.Select((r, i) => "@res" + i));
// This is NOT vulnerable to classic SQL Injection because resourceParams
// does NOT contain user data; only the parameter names.
// However, a large number of items in resources could result in degenerate
// or "too many parameter" queries so limit guards should be used.
var sql = string.Format("SELECT [Resource No_] where [Resource No_] In ({0})",
resourceParams);
var cmd = conn.CreateCommand();
cmd.CommandText = sql;
// Assign values to placeholders, using the same naming scheme.
// Parameters prevent SQL Injection (accidental or malicious).
int i = 0;
foreach (var r in resources) {
cmd.Parameters.AddWithValue("@res" + i, r);
i++;
}