如何在VB.NET中将SQL查询的结果分配给多个变量?

时间:2012-03-30 16:28:59

标签: sql vb.net

这是我第一次尝试编写一个从头开始访问数据库的程序,而不是简单地修改我公司的现有程序。这也是我第一次使用VB.Net 2010,因为我们的其他程序是用VB6和VB.NET 2003编写的。我们正在使用SQL Server 2000,但如果相关的话,应尽快升级到2008.

我可以成功连接到数据库并通过查询提取数据,并将结果分配给组合框,例如:

Private Sub PopulateCustomers()
    Dim conn As New SqlConnection()
    Dim SQLQuery As New SqlCommand
    Dim daCustomers As New SqlDataAdapter
    Dim dsCustomers As New DataSet

    conn = GetConnect()
    Try
        SQLQuery = conn.CreateCommand
        SQLQuery.CommandText = "SELECT Customer_Name, Customer_ID FROM Customer_Information ORDER BY Customer_Name"
        daCustomers.SelectCommand = SQLQuery
        daCustomers.Fill(dsCustomers, "Customer_Information")

        With cboCustomer
            .DataSource = dsCustomers.Tables("Customer_Information")
            .DisplayMember = "Customer_Name"
            .ValueMember = "Customer_ID"
            .SelectedIndex = -1
        End With

    Catch ex As Exception
        MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OkOnly, "Connection Error !!")
    End Try

    conn.Close()

End Sub

执行拉取单个字段的查询并使用ExecuteScalar将其分配给变量也没有问题。我没有设法弄清楚如何做(并且似乎无法找到正确的搜索术语组合以在其他地方找到它)是如何执行将返回单行然后在其中设置各种字段的查询那一行到个别变量。

如果它是相关的,这里是上面代码中引用的GetConnect函数:

Public Function GetConnect()
     conn = New SqlConnection("Data Source=<SERVERNAME>;Initial Catalog=<DBNAME>;User Id=" & Username & ";Password=" & Password & ";")
     Return conn
End Function

如何执行查询以便将返回行的每个字段分配给各个变量?

2 个答案:

答案 0 :(得分:2)

您可能想看一下SqlDataReader:

    Using con As SqlConnection = GetConnect()
        con.Open()

        Using cmd As New SqlCommand("Stored Procedure Name", con)
            cmd.CommandType = CommandType.StoredProcedure

            cmd.Parameters.Add("@param", SqlDbType.Int)
            cmd.Parameters("@param").Value = id

            ' Use result to build up collection
            Using dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection Or CommandBehavior.SingleResult Or CommandBehavior.SingleRow)
                If (dr.Read()) Then
                    ' dr then has indexed columns for each column returned for the row
                End If
            End Using
        End Using
    End Using

答案 1 :(得分:0)

就像@Roland Shaw一样,我会沿着datareader路线走下去,但另一种方式。

将循环播放

dsCustomers.Tables("Customer_Information").Rows

不要忘记检查那里是否有任何行。

Google VB.Net和DataRow了解更多信息。