【问题标题】:Storing results of a DataReader into an array in VB.NET将 DataReader 的结果存储到 VB.NET 中的数组中
【发布时间】:2012-08-12 06:27:36
【问题描述】:

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

我已经看到了很多答案,但我真的找不到我想要的答案

【问题讨论】:

  • 那么为什么你更喜欢这种方法而不是使用 DataTable?

标签: vb.net datareader


【解决方案1】:

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

' 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 循环遍历结果:

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 驱动程序,但同样的方法可以用于其他流行的数据库连接器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2018-10-16
    • 2013-11-30
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多