2016-02-02 36 views
1

我使用一個SqlDataReader來檢索數據庫管理系統的一些「選擇」查詢。 到目前爲止,我使用SqlDataReader.read()在結果集中逐一讀取每一行,並逐個處理它們。當結果集很大時(意味着數百萬行數百列),使用.read()迭代非常緩慢。我問:是否有一種方法可以從SqlDataReader中讀取「塊」,這意味着像SqlDataReader.read(100)這樣的東西給了我一個結果集中接下來100行的數組?使用SqlDataReader同時讀取多個行(塊讀取)

我想過要像DataTable.Load()一樣加載內存中的所有結果集,但由於表的大小爲幾個千兆字節,因此它不適合內存。

你會推薦什麼? 非常感謝

示例代碼:

TdConnection conn; 
TdCommand cmd; 
TdDataReader reader; 
IAsyncResult res; 

conn = new TdConnection(@"xxxx;"); 
conn.Open(); 

cmd = new TdCommand(q,conn); 
res = cmd.BeginExecuteReader(); 

while (!res.IsCompleted); 

reader = cmd.EndExecuteReader(res); 
if (reader.HasRows) 
{ 
    string sb; 
    string currentout = "C:\file"; 
    string[] row = new string[reader.FieldCount]; 
    sb = ""; 
    for (int i = 0; i < reader.FieldCount; i++) 
     row[i] = reader.GetName(i); 

    sb = String.Concat(sb,String.Join("\t",row),"\r\n"); 

    File.WriteAllText(currentout,sb); 

    sb = ""; 

    /* With a test query, the following commented "while" takes 5 minutes 
    /* to iterate over a dataset with 639967 rows x 63 columns (about 300MB) 
    /* while(reader.Read()); 
    */ 

    /* With the same test query, the following "while block" takes 6 minutes 
    /* to iterate over the same dataset AND writing it on a text file 
    /* I conclude that I/O writing on text file is fast, and .Read() is very slow 
    */ 
    while(reader.Read()) 
    { 
     for (int i = 0; i < reader.FieldCount; i++) 
       row[i] = reader.GetValue(i).ToString(); 

     sb = String.Concat(sb,String.Join("\t",row),"\r\n"); 

     if (sb.Length > 100000) 
     { 
      File.AppendAllText(currentout,sb); 
      sb = ""; 
     } 
    } 
    File.AppendAllText(currentout,sb); 
} 

reader.Close(); 
reader.Dispose(); 
cmd.Dispose(); 
conn.Close(); 

的 「TD」 組件是Teradata的DBMS接口.NET(但他們表現就像 「SQL」 成分)。

+0

真正的問題在這裏:爲什麼你需要加載所有的數據? – Steve

+0

閱讀緩慢,還是處理?你有沒有簡介代碼來找到瓶頸? – LarsTech

+1

也許您可以將您的程序登錄名轉移到SQL查詢並從程序中執行該查詢。 – Chuck

回答

1

什麼是慢這裏是在循環中的字符串連接的二次成本:

sb = String.Concat(sb,String.Join("\t",row),"\r\n"); 

由於這是一個明顯的問題PERF我提交此作爲一個答案,因爲它可能解決您的問題。

如果您的應用程序很慢,輪廓也看什麼是緩慢的。

不幸的是,ADO.NET確實挺讀取數據時CPU沉重。你無能爲力。