Storing results of a DataReader into an array in VB.NET

别说谁变了你拦得住时间么 提交于 2019-12-06 05:37:15

问题


How can I store the results of a DataReader into an array, but still be able to reference them by column name? I essentially want to be able to clone the DataReader's content so that I can close the reader and still have access. I don't want to store the items in a DataTable like everyone suggests.

I've seen a lot of answers, but I couldn't really find any for what I wanted


回答1:


The easiest way I've found to do this is by populating the array with dictionaries with Strings as keys and Objects as values, like so:

' 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()

So, now you could loop through result with a for loop like this:

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

Quite similar to how you would do it if it were just the DataReader:

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

This example is using the MySQL/NET driver, but the same method can be used with the other popular database connectors.



来源:https://stackoverflow.com/questions/11978127/storing-results-of-a-datareader-into-an-array-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!