3

我的 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
4

2 回答 2

6

您可以使用SqlCommand.ExecuteScalar 方法

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))当没有返回记录时valuenothing

于 2013-09-18T17:37:29.307 回答
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()

于 2013-09-18T17:45:08.213 回答