如何将
DataReader的结果存储到数组中,但仍能按列名引用它们?我本质上希望能够克隆DataReader的内容,以便我可以关闭阅读器并仍然可以访问.我不想像所有人建议的那样将物品存放在
DataTable中.
我已经看到了很多答案,但我找不到任何我想要的东西
解决方法
我发现这样做最简单的方法是使用字符串填充数组,其中字符串为键,对象为值,如下所示:
' 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驱动程序,但相同的方法可以与其他流行的数据库连接器一起使用.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。