Visual Basic - For Data Retrieval With Low Overhead, Give The DataReader A Try (VB. NET)

The DataSet is probably the most common tool for handling data in .NET. However, if you only need to retrieve small amounts of data for the purpose of displaying it, all the overhead of the DataSet to support two-way communication between the database and your .NET program is unnecessary. With the .NET DataReader, you can retrieve a read-only, forward-only stream of data and dump it out one row at a time.

The first few steps for creating a DataReader should sound familiar. You start with a Connection, pass it a ConnectionString, create a Command object, and open the Connection. From this point, to retrieve the data, you just need to call the ExecuteReader command. The following lines of code illustrates the process if you were working with a SQL database:

  • Dim cn As SqlConnection =New SqlConnection("server=svr1;" _
  •            "uid=uid1;pwd=pw1;database=yoursqldb")
  • Dim myCMD As SqlCommand = _
  •             New SqlCommand("SELECT * FROM SomeTable", cn)
  • myCMD.CommandType = CommandType.Text
  • cn.Open
  • Dim myReader As SqlDataReader = _
  •             myCMD.ExecuteReader(CommandBehavior.CloseConnection)

Once you create the SQLDataReader, you'll treat it just like you would a Recordset in classic ADO. You repeatedly call the Read() method until the DataReader retrieves all the rows. A While loop, similar to the one in the next set of code, works wonderfully:

  • Do While myReader.Read()
  •            'get data
  • Loop

Go back