c# - C# 中查询 Mysql 中的 List<string>

标签 c# mysql list datagridview

我想在查询中使用我的列表,到目前为止我有这个:

public List<string> penalties = new List<string>();
while (myReader.Read())
{
    penalties.Add((myReader["Area"].ToString()));
}

这是为了填充我的数据 GridView 。但它不起作用。

foreach(string area in penalties)
{
   string query = "SELECT * FROM tblpenalty WHERE Area='" + area + "';";
   using (connection)
   {
      using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, connection))
      {
         DataSet ds = new DataSet();
         adapter.Fill(ds);
         dataGridView1.DataSource = ds.Tables[0];
         dataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);
      }
   }
}

最佳答案

这是我从 this solution 尝试过的& this solutionList<string> 构建参数化查询使用IN条款,在 MySqlDataParameter.SelectCommand 的帮助下用法:

string query = "SELECT * FROM tblpenalty WHERE Area IN ({0})";
string[] penaltiesArray = penalties.ToArray(); // list converted to array as in /a/6804883/
string[] parameters = penalties.Select((x, n) => "@area" + n.ToString()).ToArray();
query = string.Format(query, string.Join(",", parameters));
using (connection)
{
    using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, connection))
    {
        // iterate through the list & set parameters to data adapter
        for (int i = 0; i < parameters.Length; i++)
        {
            // use MySqlDataParameter.SelectCommand directly without additional MySqlCommand
            // and use MySqlDbType depending on data type used in target column
            adapter.SelectCommand.Parameters.Add(parameters[i], MySqlDbType.VarChar).Value = penaltiesArray[i];
        }
        DataSet ds = new DataSet();
        adapter.Fill(ds);
        dataGridView1.DataSource = ds.Tables[0];
        dataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);
    }
}

请注意,您的示例查询将被执行,并将结果插入 DataGridView反复由于foreach循环,这样你就没有得到正确的结果。使用IN保存多个值的子句是更优选的解决方案。

关于c# - C# 中查询 Mysql 中的 List<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46188550/

相关文章:

java - 所有数据结构都有抽象数据类型吗?

python - 为什么嵌套循环比扁平循环执行得快得多?

c# - 是否可以在 Visual Studio Express 版本中将 Entity Framework 与 MySQL 一起使用?

c# - linq查询中的条件语句

php - 如何使用php mysqli搜索数据库的所有表并显示答案

mysql - 从提交表 (SQL) 中获取团队的最新提交

python - 无法将列表映射到 python 中的列表列表

c# - 如何在 XAML 中使用 StringFormat 显示逗号​​分隔的数字?

c# - 通用的通用的

MySQL 清理孤立表 innoDB