Execute Scalar to trap error in case of no records returned

后端 未结 4 1504
轻奢々
轻奢々 2021-01-20 06:33

I have got this code below:

Dim lJobName As String = \"\"
SQLCommand.CommandText = \"Select JobName from Jobs where Id = @Id \"
SQLCommand.Parameters.Add(New         


        
相关标签:
4条回答
  • 2021-01-20 07:04

    I try to avoid comparing a string to Nothing, even though it does work in VB.

    The Visual Basic .NET runtime evaluates Nothing as an empty string; that is, "". The .NET Framework, however, does not, and will throw an exception whenever an attempt is made to perform a string operation on Nothing.

    Plus pseudocoder's answer wont work as currently shown (oJobname is never set to anything)

    Dim lJobName as String = String.Empty
    Dim oJobName as object = SqlCommand.ExecuteScalar()
    
    If oJobName Is Nothing Then
        'Do something with the error condition
    Else
        lJobName = oJobName.ToString
    End If
    
    0 讨论(0)
  • 2021-01-20 07:11

    I think it is possible to handle this situation in the statement of the query:

    SELECT ISNULL(FieldID,"0") FROM TableName

    and subsequently in the program validate the result:

    if then ...... else ...... endif

    0 讨论(0)
  • 2021-01-20 07:26

    Whatever the manual says, comparing to Nothing does not work. So If lJobName Is Nothing will NOT be triggered when the result set is empty.

    Comparing to DBNull.Value DID work for me:

    If lJobName Is DBNull.Value Then
        'Do something with the error condition
    Else
        'Do something with lJobName which contains a valid result.
    End If
    

    It is worth noting that when the result set is empty (i.e. no records were found), this is not an "error".

    0 讨论(0)
  • 2021-01-20 07:26

    ExecuteScalar() returns Nothing if there is an empty result set, which should be preserved when assigning into a string, so I would try this:

    Dim lJobName as String = String.Empty
    lJobName = SqlCommand.ExecuteScalar()
    If lJobName Is Nothing Then
        'Do something with the error condition
    Else
        'Do something with lJobName which contains a valid result.
    End If
    

    Of course this doesn't help you if you cause a SqlException, but it should handle the problem of no rows found in the result set.

    http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

    0 讨论(0)
提交回复
热议问题