雖然我不同意所選的答案(或許多棘手的答案)的「重複問題」,here is an answer to it它顯示了一種方法非常類似於我的以下建議。
(我已經投票決定關閉這個問題作爲一個重複,因爲有是這樣的答案,即使被埋。)
只有一個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++;
}
向我們展示如何創建此查詢。 –
在不可能的情況下創建動態字符串,因爲我不知道用戶傳遞的參數數量。 – user2739679
@Simon Whitehead :: SqlCommand cmd = new SqlCommand(SELECT [Resource No_] where [Resource No_] In(@resources),conn) – user2739679