读取 DataReader 中单个列中的每一行

Read each row in a single column in a DataReader

我用while(dr.Read()){...}。但是我在读取数据时遇到问题。 我有一个像这样的 table:

Column1

value1
value2
value3

我想获得 Value1Value2Value3

我是这样做的:

Using myDataReader As OracleDataReader = myCommand.ExecuteReader
    While (myDataReader.Read())

        Value1= myDataReader.GetValue(0).ToString().Trim()
        Value2 = myDataReader.GetValue(1).ToString().Trim()
        Value3 = myDataReader.GetValue(2).ToString().Trim()

    End While
End Using

我可以检索 Value1,但是在尝试检索 Value2Value3 时出现以下错误:

Invalid column index specified

您应该考虑使用 DataTable 来加载数据,而不是使用 and OracleDataReader。为此,请使用以下代码:

Dim dt As New DataTable
dt.Load(myCommand.ExecuteReader)

DataTable 现在将包含 DataRows 的集合。您可以使用这些将值分配给您的变量,如下所示:

Value1 = dt.Rows(0).Item(0).ToString().Trim()
Value2 = dt.Rows(1).Item(0).ToString().Trim()
Value3 = dt.Rows(2).Item(0).ToString().Trim()

这可能会解决您最初的问题,但可能会导致更多问题。正如 ADyson 在他的评论中所建议的那样:

@EmmaW. you could add a counter to your loop, so you know what row you're on and can populate the property accordingly. Bugs' suggestion is also sensible if you have a smallish number of properties. Sounds like your in-code object model doesn't really match your database though (vertical DB record structure vs horizontal object structure), which could be a sign of a conceptual design problem