Vb.net逐行拉入SQL表

时间:2014-01-20 22:55:36

标签: sql vb.net

我对使用vb.net和SQL有点新意,所以我想我会和你们一起检查一下我的工作是否有意义,或者是否有更好的方法。对于第一步,我需要读取几个表中的所有行,并按照代码需要的方式存储数据。首先我得到一个计数:

mysqlCommand = New SQLCommand("SELECT COUNT(*) From TableName")
Try
    SQLConnection.Open()
    count = myCommand.ExecuteScalar()
Catch ex As SqlException

Finally
    SQLConnection.Close()
End Try

Next

现在我只想迭代遍历各行,但是我很难分两部分,首先,我无法弄清楚会让我抓住表格的特定行的SELECT语句。我在这里看到了这个例子How to select the nth row in a SQL database table?。但是,这只是在SQL中如何做到这一点,但我不确定这会转化为vb.net调用。

其次,在上面的mycommand.ExecuteScalar()告诉VB我们期望从中返回一个数字。我相信select语句将返回一个DataRow,但我不知道哪个Execute()语句告诉脚本期望它。

提前谢谢。

1 个答案:

答案 0 :(得分:1)

一种简单的方法是使用逐行迭代的DataTable。您可以使用DataAdapter填充它。使用Using - 语句来处置/关闭实现IDisposable的对象属性,如连接:

Dim table = New DataTable
Using sqlConnection = New SqlConnection("ConnectionString")
    Using da = New SqlDataAdapter("SELECT Column1, Column2, ColumnX FROM TableName ORDER By Column1", sqlConnection)
        ' you dont need to open/close the connection with a DataAdapter '
        da.Fill(table)
    End Using
End Using

现在您可以使用循环迭代所有行:

For Each row As DataRow In table.Rows
    Dim col1 As Int32 = row.Field(Of Int32)(0)
    Dim col2 As String = row.Field(Of String)("Column1")
    ' ...' 
Next

或将表格用作DataSource用于数据绑定控件。

相关问题