这是我第一次尝试编写一个从头开始访问数据库的程序,而不是简单地修改我公司的现有程序。这也是我第一次使用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