从数据库获取数据并存储到Dictionary中

时间:2015-12-15 15:38:15

标签: c# mysql asp.net dictionary

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

DB表有两列,第一(键)浮点类型和第二(值)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;
}

1 个答案:

答案 0 :(得分:0)

接下来就是你想要的:

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或类似的方法