我的sql-query的结果是一个单一的值,我希望显示在一个标签但不知道如何。我有一个创建数据集的解决方案,将查询结果放入该数据集,并按行(0),列(0)获取,但我想有更聪明的方法。
Private myquery As String
Sub New(ByVal query As String)
myquery = query
End Sub
Public Sub query_Send()
Dim myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
Dim mycmd As SqlCommand = New SqlCommand(Me.myQuery, myconn)
Dim myTable As New DataTable
Dim previousConnectionState As ConnectionState = myconn.State
Try
If myconn.State = ConnectionState.Closed Then
myconn.Open()
Dim myDA As New SqlDataAdapter(mycmd)
myDA.Fill(myTable)
tb.text = **...**
End If
If previousConnectionState = ConnectionState.Closed Then
myconn.Close()
End If
End Try
End Sub
答案 0 :(得分:4)
您可以使用SqlCommand.ExecuteScalar Method
Dim querystr as String = "select value from MyTable where ID=5"
Dim mycmd As New SqlCommand(querystr, connection)
dim value as Object = mycmd.ExecuteScalar()
您可以将value
放入文本框。 ExecuteScalar返回结果集第一行的第一个值(相当于row(0).column(0)
)当没有返回记录时,value
为nothing
。
答案 1 :(得分:0)
尝试更多内容:
Using myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
Dim myDA As New SqlDataAdapter()
myDA.SelectCommand = New SqlCommand(myQuery, myconn)
myDA.Fill(myTable)
Return myTable
End Using
或者你可以通过
获得第一行中的第一项 myTable.Rows(0).ItemArray(0).ToString()