简体   繁体   中英

Cannot read SqlDataReader Object

Trying to get response from my azure db I am using the recommended microsoft snippet

Dim sb As StringBuilder = New StringBuilder()
sb.Append("select top 1 runname from vNameCode")
'sb.Append("where untgscod = ")
Dim sql As String = sb.ToString()
Using command As SqlCommand = New SqlCommand(sql, connection)
    Using reader As SqlDataReader = command.ExecuteReader()
        While reader.Read()
            Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1))
        End While

but as soon as I try to read the values I get the error:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

I get an object back but just cannot read it in the recommended way. Any ideas what I am doing wrong?

Since you are getting runname from the table vNameCode but you are trying to access two values from the reader .

Do either of one changes:

  1. Include the corresponding values in the SELECT statement.
  2. Remove reader.GetString() from the Console.WriteLine

Try Below

Dim sb As StringBuilder = New StringBuilder()
sb.Append("select top 1 runname from vNameCode")     
Dim sql As String = sb.ToString()
Using command As SqlCommand = New SqlCommand(sql, connection)
    Using reader As SqlDataReader = command.ExecuteReader()
        While reader.Read()
            Console.WriteLine("{0}", reader.GetString(0))
        End While
    End Using
End Using

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM