2012-03-30 82 views
0

這是我第一次嘗試編寫一個從頭開始訪問數據庫的程序,而不是簡單地修改我公司的現有程序。這也是我第一次使用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 

如何執行查詢,從而返回的行各個變量的各個領域分配?

回答

0

像@Roland肖,我會下去DataReader的路線,但用其它方法。

將遍歷

dsCustomers.Tables("Customer_Information").Rows 

不要忘記檢查,看看是否有沒有任何行。

谷歌VB.Net和DataRow獲取更多信息。

+0

雖然DataReader路線可能是最好的(而且我最終走的路),但我仍然指定這個答案作爲回答具體問題的最佳答案。 – 2012-04-03 13:13:16

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 
+0

我終於坐了下來,對SqlDataReader的讀了起來,不知道爲什麼,我沒有它撿起當我第一次看它,必須有對面有些寫的不好的教程來了。我現在正在使用DataReader,它工作正常。 (雖然我挑對方的回答最佳,我會給予好評這一個,以及如果我能。) – 2012-04-03 13:15:09

+1

大多數教程直行到數據集的數據感知控件,因爲奇才和一點成立的,你最終看起來像一個專業人士,但作爲一個餅乾。所以恭喜你的晉升。 :) – 2012-04-03 14:51:37

相關問題