确定查询是否在 vb.net 中返回“无行”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19088410/
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:17:27  来源:igfitidea点击:

Determining if a query returns 'no rows' in vb.net

sqlsql-servervb.net

提问by Lorenzo Salamante

I am using MS SQL Server as my database and VB.NET as my back-end.

我使用 MS SQL Server 作为我的数据库和 VB.NET 作为我的后端。

I want to determine if my query in sql command text returns no rows. I tried to have a query that returns no rows, and then give its value to a text box which became 0. (integer)

我想确定我在 sql 命令文本中的查询是否不返回任何行。我试图有一个不返回任何行的查询,然后将其值赋予一个变为 0 的文本框。(整数)

The problem now, is that when I test it in an If condition, it doesn't work. The code is like this:

现在的问题是,当我在If 条件下测试它时,它不起作用。代码是这样的:

If (Query that returns no rows) = 0 Then
'condition
Else
'condition
End If

I tried a blank string, but it still does not work. Please help! If possible, please give the simples solution to the problem. Thank you in advance!

我尝试了一个空白字符串,但它仍然不起作用。请帮忙!如果可能,请给出问题的简单解决方案。先感谢您!

回答by Deepshikha

@podiluska is right. You will have to execute the command. As I can see you have assigned value for the CommandText property of Command object that's the query you want to execute. In order to execute the command, you must have an open active connection followed by call to Execute method on command object. Following pseudo code might help:

@podiluska 是对的。您将不得不执行该命令。正如我所看到的,您已经为 Command 对象的 CommandText 属性分配了值,该属性是您要执行的查询。为了执行命令,您必须有一个打开的活动连接,然后调用命令对象上的 Execute 方法。以下伪代码可能会有所帮助:

Public Sub Temp(ByVal connectionString As String)
    Dim queryString As String = _
       " select * from example where id = 999;" 
    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(queryString, connection)
        connection.Open()
        Dim reader As SqlDataReader = command.ExecuteReader()
        Try 
            If reader.Read() Then
               'If condition
            Else
               'condition with  no results
            End If
        Finally 
            reader.Close()
        End Try 
     End Using 
End Sub

回答by mabees

        Dim RowsReturned As Integer
        Cmd.CommandText = "SELECT * FROM tblExample WHERE PKeyNo =999"
        cmd.CommandType = CommandType.Text


        RowsReturned = cmd.ExecuteScalar()

        If RowsReturned = 0 Then
                'No rows
        Else 
           'Has Rows