我会尽力解释这一点,但不可否认的是,我几个月没有尝试太多,所以我不仅生气了,我也不擅长和你在一起。
我正在使用可视化Web开发人员和asp,vb是sql db背后的代码。
如果我从表中选择一列,例如:
sqlCmd.CommandText = "SELECT Username, W1, W2, W3, W4 FROM tablename"
假设此表中有多行,这些列中包含数据。
当我做一个datareader,或者我是如何被展示的时候,我宣布博士为:
Dim dr As Data.SqlClient.SqlDataReader
我可以使用选定的项目,例如:
dr.item(0)
dr.item(1)
等
但我可以使用的唯一项目是选择的第一行项目。如何选择表中的所有行。或者我如何使用dr.item处理多行数据或以某种方式告诉它移动到下一行,以便dr.item(0)成为表中第二行的用户名。
我希望这是有道理的,如果这是一个愚蠢的问题,我很抱歉。我提前感谢时间和帮助。谢谢你们。
答案 0 :(得分:4)
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
方法运行良好,但是如果您想要选择所有行并且可以将所有行加载到内存中,则可以使用DataTable
代替。然后你也可以通过索引器访问每一行,如数组或列表:
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
答案 1 :(得分:1)
要遍历数据表行,您需要使用以下方法:
while dr.read()
Dim col1=dr.item(0)
Dim col2=dr.item(1)
End while
这样你就可以拥有所有行的所有属性。