Gunakan bilangan parameter dinamik ke parameter SQL dalam klausa
parameterisasi setiap nilai
<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>
Atas ialah kandungan terperinci Bagaimanakah saya boleh memarameterkan klausa SQL dengan selamat dengan bilangan argumen yang dinamik?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!