如何检查DataReader的值是否不为空?

4
我正在编写VB.Net代码,通过SQL查询读取Oracle表格。
SQL查询可能会返回一些空列。我试图检查这些列是否为空,但是我收到了错误“System.InvalidCastException”类型的异常在Oracle.DataAccess.dll中发生,但未在用户代码中处理。该列包含一些Null数据 以下是我的代码:
Dim Reader as OracleDataReader 
'Execute the query here...

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

有没有想法如何检查列是否为空?

谢谢

3个回答

7

Nothing表示对象未被初始化,DBNull表示数据未定义/缺失。有几种检查方法:

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

GetDateTime方法存在问题,因为您要求将一个非值转换为DateTime。而Item()返回的是Object类型,可以在转换之前轻松进行测试。

 ' 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))

对于DateTime转换器,您需要决定返回什么。 我更喜欢逐个处理它们。


2

在将值转换为日期之前,您需要检查该字段是否为空。

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

0
使用泛型函数与扩展,会让事情变得更简单。
Imports System.Runtime.CompilerServices

<Extension()>
Public Module DataReaderExtensions
  Public Function GetValue(Of T)(ByVal drVar As Object) As T
    If drVar.Equals(DBNull.Value) Then
        ' Value is null, determine the return type for a default
        If GetType(T).Equals(GetType(String)) Then
            Return CType(CType("", Object), T)
        Else
            ' If it's anything else just return nothing
            Return CType(Nothing, T)
        End If
    Else
        ' Cast the value into the correct return type
        Return CType(drVar, T)
    End If
  End Function
End Module

你可以这样调用它

dr.Item("abc").GetValue(string)
dr.Item("def").GetValue(Nullable(of Date))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接