tye
tye

Reputation: 199

vb net SQl query problem

im trying to retrieve some data using a reader in vb.net. I dont have any issue retrieving certain columns of the data for each row but i want to retrieve all data in each row. I've tried a couple of different things with the getstring() command but it isnt working and i cant seem to find any help googling the issue. my code is this

Private Function QueryDown(ByVal queryString)
    Dim returnInfo As New StringBuilder
    Try
        Dim newQuery As String() = Split(queryString, ":")
        For Each Query In newQuery
            Dim cmd As New MySqlCommand(Query, connection1)
            Dim reader As MySqlDataReader
            reader = cmd.ExecuteReader()

            While reader.Read()
                For a = 0 To reader.FieldCount
                    Dim strng As String = reader.GetString(a)
                    returnInfo.Append(strng & ",")
                Next

                returnInfo.Append(";")
            End While
            reader.Close()
        Next
    Catch ex As Exception
        console("Error with MySQL: " & ex.Message)
        Return ex.Message
    End Try
    Return returnInfo.ToString
End Function

sorry the error i get when using this code is

There is already an open DataReader associated with this Connection which must be closed first

but if i change getstring(a) to getstring(1) everything is fine, im confused. any help here would be great, i want to formatted code to come back column,column,coloumn;nextrow, as you can see (i hope). Because each of my table has a different amount of coloumns and i want to be able to use the same function for each one. thanks again.

Upvotes: 2

Views: 515

Answers (1)

manji
manji

Reputation: 47968

Upper limit is reader.FieldCount - 1 not reader.FieldCount in:

For a = 0 To reader.FieldCount - 1

when a reaches reader.FieldCount there is an exception => reader.Close() is not executed => I suppose you call this function (or another) to open a new reader with the same connection => error.

When you call getstring(1) its working because 1 is within [0, FieldCount-1]

Update:

As @Zach Green said, try to always use using when ever possible which is a replacement for try...finally{ .Dispose() }: the dispose in finallyis applied to object beeing "used" and calling for DataReader/DataConnection it will call .Close() for you.

Upvotes: 2

Related Questions