2015-01-04 163 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