Link to home
Start Free TrialLog in
Avatar of sacul
sacul

asked on

dataset error

Hello Experts,

I have a question about datasets. I connect to several databases  and load the query result into a dataset that I write to an XML file. The first connection works fine but when I try it a second time in the same sub I get this error:

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



Posted below is the code that executes:

Try
            conn.Open()
            mycommand.Connection = conn

            mycommand.CommandText = "SELECT * FROM test WHERE testNum= " & Textbox1.Text & " AND Type = 'Contract'"
            myRead = mycommand.ExecuteReader

            While myRead.Read()
                ...assign variables...
            End While

            myRead.Close()
            conn.Close()

            myAdapter.SelectCommand = mycommand
            myAdapter.Fill(myData)
            myData.WriteXml("C:\Dataset.xml", XmlWriteMode.WriteSchema)
            myData.Clear()

            '****************Second connection*********************

            conn.ConnectionString = "server=192.16.......~"
            conn.Open()
            mycommand.Connection = conn
            mycommand.CommandText = "SELECT * FROM test2 WHERE test2Num= " & Textbox1.Text
            myRead = mycommand.ExecuteReader

            While myRead.Read()
              ...assign varibales...
            End While

            myAdapter.SelectCommand = mycommand
            myAdapter.Fill(myData)
            myData.WriteXml("C:\totalNumberDataset.xml", XmlWriteMode.WriteSchema) <----HERE is where the exception is thrown

        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            conn.Close()
        End Try

Any help is greatly appreciated


Thanks,

Zac
ASKER CERTIFIED SOLUTION
Avatar of pradeepsudharsan
pradeepsudharsan

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pradeepsudharsan
pradeepsudharsan

       myRead.Close()
            conn.Close()
You missed these lines in Second connection

While myRead.Read()
              ...assign varibales...
            End While
myRead.Close() 'Close the reader and use adapter
 conn.Close() is not needed
Avatar of sacul

ASKER

Awesome...

I just missed that part. You spend enough hours looking at it and you go code blind thats for sure

Thanks for the help.

Thanks,

Zac