Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Going through a DataReader twice

I have the following code which does what it's supposed to do:

objSQLCommand = New SqlCommand("select * from table1", objSQLConnection)

objSQLCommand.Connection.Open()
objSQLDataReader = objSQLCommand.ExecuteReader()

While objSQLDataReader.Read()
    objStringBuilder.Append(objSQLDataReader("forename"))
    objStringBuilder.Append("<br /><br />")
    objStringBuilder.Append(objSQLDataReader("surname"))
    objStringBuilder.Append("<br /><br />")
End While

objSQLDataReader.Close()
objSQLCommand.Connection.Close()

But I need to loop through the objSQLDataReader 1 more time. How would I do that?

like image 531
oshirowanen Avatar asked Mar 30 '11 14:03

oshirowanen


2 Answers

Three options:

  • execute the query twice (readers like this are forwards only)
  • buffer the data locally, then process it twice (the "buffer" could be an object collection, XML, a DataTable (spit), etc)
  • write both outputs at the same time; i.e. for each row, write the first format to the first output, then the second format to the second output

I'd probably aim at the last option, as it involves no buffering or repetition; however I would move the logic for each method into 2 distinct methods

like image 106
Marc Gravell Avatar answered Nov 03 '22 00:11

Marc Gravell


Loop through data reader only once and load your data into some sort of an instantiated collection (e.g. List<MyDataObject>) that you can reference later to loop through again and again, and again.

like image 34
Kon Avatar answered Nov 03 '22 00:11

Kon