以下是代码:
Function getData(ByVal id As String)
Dim reader As SqlClient.SqlDataReader
Dim statement As String
Dim count As Integer
Dim temp As Integer
statement = "SELECT * FROM General WHERE accountid='" + id + "'"
Conn.Open()
Comm = New SqlClient.SqlCommand(statement, Conn)
reader = Comm.ExecuteReader()
count = reader.FieldCount
Dim Data(count) As String
If reader.HasRows Then
For temp = 0 To count
Data(temp) = (reader.Item(temp))
Next temp
Else
Console.WriteLine("No rows found.")
End If
reader.Close()
Conn.Close()
Return Data
End Function
当我运行代码时,HasRows
字段为true,但reader.Item(temp)
给出错误
没有数据时无效尝试读取。
答案 0 :(得分:3)
您需要While reader.Read()
循环。读者从行索引-1开始; <()将前进到第一行(好吧,获取它)然后你可以处理它。
这就是为什么你的HasRows返回true但你无法检索字段 - 你还没有找到第一行。
您可能想要这样做:
If reader.HasRows Then
While reader.Read()
For temp = 0 To count
Data(temp) = (reader.Item(temp))
Next temp
End While
Else
Console.WriteLine("No rows found.")
End If