Use the number of dynamic parameters to parameter SQL in clause
Parameterization per value
<code class="language-sql">SELECT * FROM Tags WHERE Name IN ('ruby','rails','scruffy','rubyonrails') ORDER BY Count DESC</code>
<code class="language-csharp">string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" }; string cmdText = "SELECT * FROM Tags WHERE Name IN ({0})"; string[] paramNames = tags.Select((s, i) => "@tag" + i.ToString()).ToArray(); string inClause = string.Join(",", paramNames); using (SqlCommand cmd = new SqlCommand(string.Format(cmdText, inClause))) { for (int i = 0; i < tags.Length; i++) { cmd.Parameters.AddWithValue(paramNames[i], tags[i]); } // ... 执行查询 ... }</code>
<code class="language-sql">cmd.CommandText = "SELECT * FROM Tags WHERE Name IN (@tag0, @tag1, @tag2, @tag3)" cmd.Parameters["@tag0"] = "ruby" cmd.Parameters["@tag1"] = "rails" cmd.Parameters["@tag2"] = "scruffy" cmd.Parameters["@tag3"] = "rubyonrails"</code>
The above is the detailed content of How Can I Securely Parameterize an SQL IN Clause with a Dynamic Number of Arguments?. For more information, please follow other related articles on the PHP Chinese website!