将 DataReader 的结果存储到 VB.NET 中的数组中 [英] Storing results of a DataReader into an array in VB.NET
问题描述
如何存储 DataReader 到一个数组,但仍然能够通过列名引用它们?我基本上希望能够克隆 DataReader 的内容,以便我可以关闭阅读器并仍然可以访问.我不想将项目存储在 DataTable 就像大家建议的那样.
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
推荐答案
我发现最简单的方法是用字典填充数组,以字符串为键,以对象为值,如下所示:
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()
所以,现在你可以像这样使用 for 循环遍历结果:
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
非常类似于如果它只是 DataReader:
Quite similar to how you would do it if it were just the DataReader:
While Dr.Read()
Console.Write(Dr("ColName"))
End While
这个例子使用的是 MySQL/NET 驱动程序,但同样的方法也可以用于其他流行的数据库连接器.
This example is using the MySQL/NET driver, but the same method can be used with the other popular database connectors.
这篇关于将 DataReader 的结果存储到 VB.NET 中的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!