【问题标题】:Getting data from Database and storing into Dictionary从数据库中获取数据并存储到字典中
【发布时间】:2015-12-15 15:38:15
【问题描述】:

我正在尝试从 MySQL 表中获取数据并将其存储到字典中。我知道我可以通过循环来做到这一点,但数据库表包含超过一百万个元组并且会减慢进度。有什么方法可以做到这一点而不必循环所有条目?

DB 表有两列,1st(key) float 类型和 2nd(value) varchar。

我目前的做法:

public static Dictionary<Single, string> GetData()
{
   Dictionary<Single, string> dic= new Dictionary<Single, string>();
   string query = "select * from table;";
   if (OpenConnection() == true)
   {
        try
        {
            MySqlCommand cmd = new MySqlCommand(query, connection);
            MySqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {

               //Something to store DB columns into dictionary without having to loop.  

            }
            reader.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
   }
   return dic;
}

【问题讨论】:

  • 为什么你有一个规则作为而不必循环?使用循环有什么错误
  • 基本思想是在与主线程不同的线程上执行长进程以不挂起GUI。您可以显示进度条或其他类型的等待消息。
  • 其实这只是更大问题的一小部分,我不能花太多时间在上面。循环将使我的工具的整体性能非常缓慢。
  • 首先,你的表是不是只有2列?只选择你需要的和你需要的部分数据,而不是整百万

标签: c# mysql asp.net dictionary


【解决方案1】:

接下来就是你想要的:

try
    {
        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataAdapter msda = new MySqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        msda.Fill(ds);
        your_control.DataSource = ds;
        your_control.DataBind();
        //your control means some repeater, or gridview, or anything else, which may show all your elements together.
    }

但您还应该考虑,如果您有数百万条记录,最好将它们部分选中。例如,每页 100 条记录,使用 row_number 或类似方法

【讨论】:

  • 我可以将DataSet中的数据提取到字典中吗?
  • @AbdulRehman 无论如何你都必须使用循环。我想提供 foreach 循环
猜你喜欢
  • 2019-12-20
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多