Creating a simple SQL data reader

Posted in: Data Access
By dePoPo
Mar 2, 2009 - 10:36:43 PM

This code sample shows how to construct a datareader which executes an SQL statement and then loops the resulting data set for processing.

Note that a datareader is only suitable for read-only access, if you also want to be able to edit, delete or append records you need to use a table object.



Dim db_connection As SqlConnection
Dim db_command As SqlCommand
Dim datareader As SqlDataReader
db_connection = New SqlConnection(My.Settings.MyConnectionString)
db_connection.Open()
db_command = New SqlCommand("SELECT * FROM tablename", db_connection)
datareader = db_command.ExecuteReader
If datareader.HasRows = True Then
  While datareader.Read
  'process records here
  End While
End If
datareader.close()
db_connection.close


Visitor Comments