這是我第一次嘗試編寫一個從頭開始訪問數據庫的程序,而不是簡單地修改我公司的現有程序。這也是我第一次使用VB.Net 2010,因爲我們的其他程序是用VB6和VB.NET 2003編寫的。我們正在使用SQL Server 2000,但如果相關的話,應該儘快升級到2008年。如何將SQL查詢的結果分配給VB.NET中的多個變量?
我可以成功連接到數據庫,並通過查詢獲取數據和分配,例如,結果到組合框,比如這裏:
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
如何執行查詢,從而返回的行各個變量的各個領域分配?
雖然DataReader路線可能是最好的(而且我最終走的路),但我仍然指定這個答案作爲回答具體問題的最佳答案。 – 2012-04-03 13:13:16