gpt4 book ai didi

c# - MySQL 查询在 C# 中不起作用,但直接在数据库上执行时有效

转载 作者:行者123 更新时间:2023-11-29 11:00:35 30 4
gpt4 key购买 nike

在我的 C# 项目中,我尝试通过使用逗号分隔的字符串列表动态填充 WHERE 子句来查询数据库表:

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
}

当我运行上述命令时,没有返回任何行。但是,当我通过 MySQL Workbench 直接在数据库上运行 SQL 查询时,会找到以下行:

SELECT * FROM products WHERE LOWER(name) IN ('a', 'b', 'c');
// 3 rows found

为什么这在我的 C 代码中不起作用?

最佳答案

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 将用正确的参数替换该值。

关于c# - MySQL 查询在 C# 中不起作用,但直接在数据库上执行时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42360639/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com