不幸的是,SQL参数不能以这种方式 解析 ,换句话说,后端不只是构建一个安全字符串来替换每个参数的值。相反,您必须动态构建参数列表:
cmd.CommandText = @"select column_name, table_name from information_schema.columns where table_name in (@p1, @p2, @p3)"; // This can be built dynamically
然后添加每个参数:
cmd.Parameters.AddWithValue("@p1", "tableOne");cmd.Parameters.AddWithValue("@p2", "tableTwo");cmd.Parameters.AddWithValue("@p3", "tableThree");如果在运行时之前还不知道这些参数,那么您当然可以在循环中添加这些参数:
for(var i = 0; i < myParams.length; i++){ cmd.Parameters.AddWithValue("@p" + i.ToString(), myParams[i]);}如果您将表列表存储在中
enum,或者可以转义它们或使用正则表达式对其进行验证,那么仅自己构建原始SQL而根本不使用参数也将是相当安全的。
当然,这是我使用PostgreSQL的重要原因之一;对数组的本机支持。



