Retrieving data from a SQL Server Database
As discussed in Retrieving Data from an Access Database, the DataReader object is one of the easiest ways to programmatically read data from a databace. The same is true for returning rows of data from a SQL Server database. A brief overview of what is required to retrieve data from a SQL Server database is as follows:
- Create a connection to the database
- Create a SQL query, with or without parameters, to access the required data
- Assign the SQL Query to a SQLCommand object
- Execute the SQLCommand to retrieve the records
Steps 1 to 3 have been covered in the posts detailing how to connect to a SQL Server Database and how to add parameters to a SQL Server query. The code snippet below assumes that you have read and understand those posts, so if you don't it's time to go back and familiarise yourself again.
'declare a DataReader
Dim dr As SqlDataReader 'For a SQL Server database
'populate the datareader with the results of the command
dr = cmd.ExecuteReader()
'create a loop to read values from the datareader
While dr.Read()
'gain access to the fields using something like below
Dim strValue As String = dr(fieldname).ToString()
End While
'close the read when done
dr.Close()