在我的C#项目中,我试图通过用逗号分隔的字符串列表动态填充List<string> productNames = new List<string>() { "A", "B", "C" };
// Construct SQL query
string names = String.Join(",", productNames.Select(n => "'" + n.ToLower() + "'").ToArray());
// names = 'a', 'b', 'c'
string query = "SELECT * FROM products WHERE LOWER(name) IN (@names);";
MySqlCommand cmd = new MySqlCommand(query, dbConn);
cmd.Parameters.AddWithValue("@names", names);
MySqlDataReader row = cmd.ExecuteReader();
while (row.Read())
{
// Zero rows returned
}
子句来查询数据库表:
SELECT * FROM products WHERE LOWER(name) IN ('a', 'b', 'c');
// 3 rows found
当我运行上面的操作时,不会返回任何行。 但是,当我通过MySQL Workbench直接在数据库上运行SQL查询时,会找到行:
{{1}}
为什么这在我的C代码中不起作用?
答案 0 :(得分:1)
Brain在他的博客文章here中对此进行了很好的解释。以下答案是这篇文章的摘录: 您需要一次添加一个数组中的值。
List<string> productNames = new List<string>() { "A", "B", "C" };
var parameters = new string[productNames.Count];
var cmd = new SqlCommand();
for (int i = 0; i < productNames.Count; i++)
{
parameters[i] = string.Format("@name{0}", i);
cmd.Parameters.AddWithValue(parameters[i], productNames[i]);
}
cmd.CommandText = string.Format("SELECT * FROM products WHERE LOWER(name) IN ({0})", string.Join(", ", parameters));
cmd.Connection = new SqlConnection(connStr);
这是一个扩展且可重复使用的解决方案
public static class SqlCommandExt
{
/// <summary>
/// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
/// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN ({paramNameRoot}))
/// </summary>
/// <param name="cmd">The SqlCommand object to add parameters to.</param>
/// <param name="values">The array of strings that need to be added as parameters.</param>
/// <param name="paramNameRoot">What the parameter should be named followed by a unique value for each value. This value surrounded by {} in the CommandText will be replaced.</param>
/// <param name="start">The beginning number to append to the end of paramNameRoot for each value.</param>
/// <param name="separator">The string that separates the parameter names in the sql command.</param>
public static SqlParameter[] AddArrayParameters<T>(this SqlCommand cmd, IEnumerable<T> values, string paramNameRoot, int start = 1, string separator = ", ")
{
/* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually.
* Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
* IN statement in the CommandText.
*/
var parameters = new List<SqlParameter>();
var parameterNames = new List<string>();
var paramNbr = start;
foreach(var value in values)
{
var paramName = string.Format("@{0}{1}", paramNameRoot, paramNbr++);
parameterNames.Add(paramName);
parameters.Add(cmd.Parameters.AddWithValue(paramName, value));
}
cmd.CommandText = cmd.CommandText.Replace("{" + paramNameRoot + "}", string.Join(separator, parameterNames.ToArray()));
return parameters.ToArray();
}
}
你可以在你的方法中调用它,如
var cmd = new SqlCommand("SELECT * FROM products WHERE LOWER(name) IN ({name})");
cmd.AddArrayParameters(new int[] {"A", "B", "C" }, "name");
请注意,sql语句中的"{name}"
与我们发送给AddArrayParameters
的参数名称相同。 AddArrayParameters
将使用正确的参数替换该值。
答案 1 :(得分:0)
当您对IN使用参数化查询时,您应该为每个值使用一个参数。我的意思是你不应该使用值为“A,B,C”的单个参数。而不是这样你应该使用这样的查询。
{{1}}
关于你今天的另一个问题,我为此写了一个例子。请检查this answer
答案 2 :(得分:0)
您的C#代码无效,因为
cmd.Parameters.AddWithValue("@names", names);
您传递的是单个值names
。 不作为三个参数。
所以你的等效sql查询就像
SELECT * FROM products WHERE LOWER(name) IN ("'a', 'b', 'c'");
并且找不到匹配项。要了解有关IN clause
及其误解的更多信息,请查看这篇精彩文章Arrays and Lists in SQL Server
理想情况下,参数必须是单个值。你可以这样做
SELECT * FROM products WHERE LOWER(name) IN (@name1, @name2, @name3);
简单而干净。 但是你也可以尝试在单个参数中传递多个值,就像在这里完成一样 Parameterize an SQL IN clause 和Having multiple values assigned to a single ADO.Net SqlClient parameter