繁体   English   中英

在VB.net中处理DBNull异常

[英]Handling DBNull exception in VB.net

我正在尝试从数据库读取数据时处理DBNull异常。 这是我的代码:

...
Dim SQLRDAs SqlDataReader
...
val1= GetStringFromDB(Trim(SQLRD("Name")))
val2= GetStringFromDB(Trim(SQLRD("Level")))
val2= GetStringFromDB(Trim(SQLRD("blahblah")))
...
Public Function GetStringFromDB(ByVal inputValue) As String
     Dim outputValue As String

     If IsDBNull(inputValue) Then
         outputValue = "null"
     Else
         outputValue = inputValue
     End If

     Return outputValue
End Function

但是仍然Conversion from type 'DBNull' to type 'String' is not valid. 错误。 怎么了?

在我看来,这不仅仅是一个简单的移位错误。 您检查Not IsDbNull(..)但行为就像dbnull!

Public Function GetStringFromDB(ByVal inputValue) As String
   Dim outputValue As String

   If Not IsDBNull(inputValue) Then
       outputValue = inputValue
   Else
       outputValue = "null"
   End If

   Return outputValue
End Function

这应该可以解决问题!

您已经混合了条件。

更改

 If Not IsDBNull(inputValue) Then
     outputValue = "null"
 ' ....

 If IsDBNull(inputValue) Then
     outputValue = "null"
 ' ....

编辑 :在执行DBNull检查之前执行Trim 所以我认为那是导致您异常的原因。 将您的代码更改为:

GetStringFromDB(SQLRD("Name")).Trim

在我看来,好像您尝试Trim DBNull值。

GetStringFromDB(SQLRD("Name")).Trim()或在GetStringFromDB内部

编辑:我将这些东西包装到一个扩展中,使其更易于使用并且不会使您的代码混乱。

  <Runtime.CompilerServices.Extension()>
  Public Function ReadString(ByVal this As SqlDataReader, ByVal index As Integer) As String
    Return If(Convert.IsDBNull(this.Item(index)), String.Empty, DirectCast(this.Item(index), String))
   End Function

    <Runtime.CompilerServices.Extension()>
    Public Function ReadString(ByVal this As SqlDataReader, ByVal columnName As String) As String
        Return If(Convert.IsDBNull(this.Item(columnName)), String.Empty, DirectCast(this.Item(columnName), String))
    End Function

IsDBNull检查值是否丢失。 它不等同于Nothing或String.Empty。 您确定您的inputValue包含DBNull.Value吗?

我将以这种方式更改您的代码:

 If String.IsNullOrEmpty(inputValue) OrElse IsDBNull(inputValue) Then 
     outputValue = "null" 

另请注意,您未指定inputValue的类型,在我的回答中,我假定为As String

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM