2012-08-15 57 views
2
陣列

我怎麼能一個DataReader的結果存儲到一個數組,但仍然可以通過列名中引用它們?我基本上希望能夠克隆DataReader的內容,這樣我可以關閉閱讀器並仍然可以訪問。我不想像所有人所暗示的那樣在DataTable中存儲這些項目。存儲一個DataReader結果到VB.NET

我見過很多答案,但我真的不能找到任何對我想要的東西

+0

那麼,爲什麼你喜歡這種方法使用一個DataTable? – Doug 2013-04-26 16:23:03

回答

6

我發現要做到這一點是通過填充數組與字符串詞典的按鍵的最簡單方法所以

' Read data from database 
Dim result As New ArrayList() 
Dr = myCommand.ExecuteReader() 

' Add each entry to array list 
While Dr.Read() 
    ' Insert each column into a dictionary 
    Dim dict As New Dictionary(Of String, Object) 
    For count As Integer = 0 To (Dr.FieldCount - 1) 
     dict.Add(Dr.GetName(count), Dr(count)) 
    Next 

    ' Add the dictionary to the ArrayList 
    result.Add(dict) 
End While 
Dr.Close() 

,現在你可以遍歷結果用了這樣的循環:和對象的價值觀,像這樣

For Each dat As Dictionary(Of String, Object) In result 
    Console.Write(dat("ColName")) 
Next 

神似你會怎麼做,如果它是算了筆他的DataReader:

While Dr.Read() 
    Console.Write(Dr("ColName")) 
End While 

這個例子是使用MySQL/NET驅動器,但相同的方法可以與其他流行的數據庫連接器一起使用。