在VB.NET中将DataReader的结果存储到数组中

Bra*_*eau 4 vb.net datareader

如何将DataReader的结果存储到数组中,但仍能按列名引用它们?我本质上希望能够克隆DataReader的内容,以便我可以关闭阅读器并仍然可以访问.我不想像所有人建议的那样将项目存储在DataTable中.

我已经看到了很多答案,但我找不到任何我想要的东西

Bra*_*eau 8

我发现这样做的最简单方法是使用字符串填充数组,其中字符串为键,对象为值,如下所示:

' 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()
Run Code Online (Sandbox Code Playgroud)

所以,现在你可以使用for循环遍历结果,如下所示:

For Each dat As Dictionary(Of String, Object) In result
     Console.Write(dat("ColName"))
Next
Run Code Online (Sandbox Code Playgroud)

非常类似于如果它只是DataReader你会怎么做:

While Dr.Read()
    Console.Write(Dr("ColName"))
End While
Run Code Online (Sandbox Code Playgroud)

此示例使用MySQL/NET驱动程序,但相同的方法可以与其他流行的数据库连接器一起使用.