2015-01-04 165 views
2

我在写一个通过SQL查询读取Oracle表的VB.Net代码。如何检查DataReader值是否为空?

SQL查询可能会返回一些空列。我试图检查这些列是否为空,但我收到错误在Oracle.DataAccess.dll中发生了类型'System.InvalidCastException'的异常,但未在用户代码中处理。该列包含一些空数据

这里是我的代码:

Dim Reader as OracleDataReader 
'Execute the query here... 

Reader.Read() 
If IsNothing(Reader.GetDateTime(0)) Then 'Error here !! 
     'Do some staff 
end if 

有没有人对如何检查列是否为空,请的想法?

谢谢

回答

3

Nothing指目标尚未被初始化,DBNull意味着数据没有被定义/缺失。有几种方法来检查:

' The VB Function 
If IsDBNull(Reader.Item(0)) Then... 

GetDateTime方法是有问题的,因为你问到一个非值转换为DateTime。 Item()返回在转换之前可轻松测试的对象

' System Type 
If System.DBNull.Value.Equals(...) 

您也可以使用DbReader。这仅适用于序索引,而不是列名:

If myReader.IsDbNull(index) Then 

此基础上,你可以放在一起的功能无论是作为共享类成员或修改成扩展到测试的DBNull并返回一个默认值:

Public Class SafeConvert 
    Public Shared Function ToInt32(Value As Object) As Integer 
     If DBNull.Value.Equals(Value) Then 
      Return 0 
     Else 
      Return Convert.ToInt32(Value) 
     End If 
    End Function 

    Public Shared Function ToInt64(Value As Object) As Int64 
     If DBNull.Value.Equals(Value) Then 
      Return 0 
     Else 
      Return Convert.ToInt64(Value) 
     End If 
    End Function 

    ' etc 
End Class 

用法:

myDate = SafeConvert.ToDateTime(Reader.Item(0)) 

对于日期时间转换器,你就必须决定如何返回。我更喜欢单独做这些事情。

1

您需要检查该字段为空你的值转换为日期之前。

If (Reader.IsDBNull(0)) Then 
    'Null: Do not call GetDateTime 
End If 

If (Not Reader.IsDBNull(0)) Then 
    'Not null: Retrieve the datetime. 
    Dim dt As DateTime = Reader.GetDateTime(0) 
End If