Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop Through Data From A Database

Database

Loop Through Data From A Database

by  ca8msm  Posted    (Edited  )
Here are two ways to read data from a database and iterate through the results. The first way will use a Reader object (from the SQLClient class which will read a SQL Server database) and loop through the results using the .Read command of the Reader. The second way will again use the SQLClient class, but this time we will load the data into a DataTable and then loop through each row of the table.

Using a DataReader

Code:
	Dim MyDataReader As System.Data.SQLClient.SqlDataReader
        Dim MyCommand As System.Data.SQLClient.SqlCommand
        Dim MyConnection As System.Data.SQLClient.SqlConnection
        
	MyConnection = New System.Data.SQLClient.SqlConnection("server=127.0.0.1; initial catalog=Northwind;uid=USERNAME;pwd=PASSWORD")
        MyConnection.Open()
        MyCommand = New System.Data.SQLClient.SqlCommand
        MyCommand.Connection = MyConnection
        MyCommand.CommandText = "SELECT * FROM products"
        MyDataReader = MyCommand.ExecuteReader()
        
	While MyDataReader.Read
		Response.Write("Name: " & MyDataReader.Item("ProductName") & "<br>")
        End While

	MyDataReader = Nothing
	MyCommand = Nothing
	MyConnection.Close()
	MyConnection = Nothing

Using a DataTable

Code:
	Dim MyConnection As System.Data.SQLClient.SqlConnection
	Dim MyDataAdapter As SQLClient.SQLDataAdapter
	Dim MyDataTable As New DataTable
	Dim MyDataRow As DataRow
	Dim strSQL As String = "SELECT FIELD1, FIELD2 FROM MYTABLE"

	MyConnection = New System.Data.SQLClient.SqlConnection("server=127.0.0.1; initial catalog=MyDatabase;uid=USERNAME;pwd=PASSWORD")
	MyConnection.Open()
	MyDataAdapter = New SQLClient.SQLDataAdapter(strSQL, MyConnection)
	MyDataAdapter.Fill(MyDataTable)

	' Loop through DataTable
	For Each MyDataRow In MyDataTable.Rows
    		Response.Write(MyDataRow.Item(0))
	Next
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top