vb.net 从 sql-query 获取单个值到文本框中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18878656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:07:39  来源:igfitidea点击:

get single value from sql-query into a textbox

vb.netdatasetstreamreader

提问by ruedi

The result of my sql-query is a single value i want display that in a lable but dont know how. I have a solution creating a dataset put the result of the query into that dataset and get it by row(0),column(0) but i guess there is a smarter way doing it.

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

回答by IvanH

You can use SqlCommand.ExecuteScalar Method

您可以使用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()

The valueyou can put to your textbox. ExecuteScalar returns first value of first row of the resultset (equivalent of row(0).column(0)) When no record is returned the valueis nothing.

value你可以把你的文本。ExecuteScalar 返回结果集第一行的第一个值(相当于row(0).column(0)) 当没有记录返回时valuenothing

回答by Derek Meyer

Try something more along the lines of:

尝试更多的东西:

    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 

Or you can just get ahold of the first item in the first row with

或者您可以使用以下命令获取第一行中的第一项

myTable.Rows(0).ItemArray(0).ToString()

myTable.Rows(0).ItemArray(0).ToString()