如何检查DataReader值是否为空?

时间:2015-01-04 12:39:59

标签: vb.net oracle

我正在编写一个VB.Net代码,它通过SQL查询读取Oracle表。

SQL查询可能会返回一些空列。我正在尝试检查这些列是否为null但是我收到错误 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 个答案:

答案 0 :(得分:4)

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 

基于此,您可以将函数组合为共享类成员或重新设置为Extensions以测试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转换器,您必须决定返回什么。我更喜欢单独做这些。

答案 1 :(得分: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

答案 2 :(得分: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))