简体   繁体   中英

How do I assign the results of an SQL query to multiple variables in VB.NET?

This is my first attempt at writing a program that accesses a database from scratch, rather than simply modifying my company's existing programs. It's also my first time using VB.Net 2010, as our other programs are written in VB6 and VB.NET 2003. We're using SQL Server 2000 but should be upgrading to 2008 soon, if that's relevant.

I can successfully connect to the database and pull data via query and assign, for instance, the results to a combobox, such as here:

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

I also have no problem executing a query that pulls a single field and assigns it to a variable using ExecuteScalar. What I haven't managed to figure out how to do (and can't seem to hit upon the right combination of search terms to find it elsewhere) is how to execute a query that will return a single row and then set various fields within that row to individual variables.

In case it's relevant, here is the GetConnect function referenced in the above code:

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

How do I execute a query so as to assign each field of the returned row to individual variables?

You probably want to take a look at the 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

Like @Roland Shaw, I'd go down the datareader route but an other way.

would be to loop through

dsCustomers.Tables("Customer_Information").Rows

Don't forget to check to see if there are any rows in there.

Google VB.Net and DataRow for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM