2013-02-17 205 views
0

我有一张包含大约5亿条记录的表格。我正在读取表格中的数据并将它们存储在Dictionary中。从数据库中读取海量数据的最快方法

编辑:我将数据装入字典,因为这些数据需要与数据从索引服务器未来的另一个卷进行比较。

我的代码如下:

public static void GetDetailsFromDB() 
{ 
    string sqlStr = "SELECT ID, Name ,Age, email ,DOB ,Address ,Affiliation ,Interest ,Homepage FROM Author WITH (NOLOCK) ORDER BY ID"; 
    SqlCommand cmd = new SqlCommand(sqlStr, _con); 
    cmd.CommandTimeout = 0; 

    using (SqlDataReader reader = cmd.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      //Author Class 
      Author author = new Author(); 

      author.id = Convert.ToInt32(reader["ID"].ToString()); 
      author.Name = reader["Name"].ToString().Trim(); 
      author.age = Convert.ToInt32(reader["Age"].ToString()); 
      author.email = reader["email"].ToString().Trim(); 
      author.DOB = reader["DOB"].ToString().Trim(); 
      author.Address = reader["Address"].ToString().Trim(); 
      author.Affiliation = reader["Affiliation"].ToString().Trim(); 
      author.Homepage = reader["Homepage"].ToString().Trim(); 

      string interests = reader["Interest"].ToString().Trim(); 
      author.interest = interests.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToList(); 

      if (!AuthorDict.ContainsKey(author.id)) 
      { 
       AuthorDict.Add(author.id, author); 
      } 

      if (AuthorDict.Count % 1000000 == 0) 
      { 
       Console.WriteLine("{0}M author loaded.", AuthorDict.Count/1000000); 
      } 
     } 
    } 
} 

这个过程是需要长时间阅读,所有500万条记录的数据库存储。另外,RAM的使用率非常高。

可以这样进行优化?还可以减少运行时间吗?任何帮助表示赞赏。

+3

你为什么要装500M记录RAM? – Mat 2013-02-17 14:23:36

+0

我需要将记录与其他一些数据进行比较。 – SKJ 2013-02-17 14:24:31

+8

那么?你有一个数据库,那些擅长搜索数据。如果您想获得相关答案,请详细说明您要实现的目标。 – Mat 2013-02-17 14:25:51

回答

3

如果我认为我的鼻子,我可以想出以下的优化:

  1. 商店序中的局部变量的字段的位置和参考使用这些有序变量在reader领域。

  2. 不要呼吁读者ToString和转换 - 刚刚得到的值出正确的类型。

  3. 检查在AuthorDict作者id的存在,只要你有ID。如果你不需要它,甚至不要创建Author实例。

    using (SqlDataReader reader = cmd.ExecuteReader()) 
    { 
        var idOrdinal = reader.GetOrdinal("ID"); 
        //extract other ordinal positions and store here 
    
        while (reader.Read()) 
        { 
         var id = reader.GetInt32(idOrdinal); 
    
         if (!AuthorDict.ContainsKey(id)) 
         { 
          Author author = new Author(); 
          author.id = reader.GetInt32(idOrdinal); 
          ... 
         } 
        } 
    }