SqlDataReader.Read
将阅读器推进到下一条记录,并true
在至少有另一行时返回:
Using conn = New SqlClient.SqlConnection(connString)
Using cmd = New SqlClient.SqlCommand("SELECT Username, W1, W2, W3, W4 FROM tablename", conn)
conn.Open()
Using dr = cmd.ExecuteReader()
While dr.Read()
Dim UserName As String = dr.GetString(0)
' ... '
End While
End Using
End Using
End Using
用于Using
尽快处置任何实施IDisposable
。它还将隐式关闭连接。
编辑:使用DataTable
如何选择表格中的所有行
上面的DataReader
方法效果很好,但是如果你想选择所有行并且可以全部加载到内存中,你可以使用 aDataTable
代替。然后您还可以通过索引器访问每一行,如数组或列表:
Dim tblUsers = New DataTable()
Using conn = New SqlClient.SqlConnection(connString)
Using da = New SqlClient.SqlDataAdapter("SELECT Username, W1, W2, W3, W4 FROM tablename", conn)
da.Fill(tblUsers)
End Using
End Using
' access a row via index: '
Dim row10 As DataRow = tblUsers.Rows(9)
Dim user10 = row10.Field(Of String)("Username")
' of course you can also iterate all rows: '
For Each row As DataRow In tblUsers.Rows
Dim userName = row.Field(Of String)("Username")
Next