如何检查DataReader值是否不为null? [英] How to check if DataReader value is not null?
问题描述
我正在编写一个VB.Net代码,该代码通过SQL查询读取Oracle表.
I'm writing a VB.Net code that reads an Oracle Table through an SQL query.
SQL查询可能返回一些空列.我正在尝试检查这些列是否为空,但是我收到错误 Oracle.DataAccess.dll中发生了类型'System.InvalidCastException'的异常,但未在用户代码中处理.该列包含一些Null数据
The SQL query may return some null columns. I'm trying to check if these columns are null or not but I'm receiving the error An exception of type 'System.InvalidCastException' occurred in Oracle.DataAccess.dll but was not handled in user code. The column contains some Null Data
这是我的代码:
Dim Reader as OracleDataReader
'Execute the query here...
Reader.Read()
If IsNothing(Reader.GetDateTime(0)) Then 'Error here !!
'Do some staff
end if
请问有人对如何检查列是否为空有想法吗?
Does anyone have an idea on how to check if a column is null please ?
谢谢
推荐答案
Nothing
表示对象尚未初始化,DBNull
表示未定义/丢失数据.有几种检查方法:
Nothing
means an object has not been initialized, DBNull
means the data is not defined/missing. There are several ways to check:
' The VB Function
If IsDBNull(Reader.Item(0)) Then...
GetDateTime
方法有问题,因为您要求它将非值转换为DateTime. Item()
返回可以在转换前 轻松测试的Object.
The GetDateTime
method is problematic because you are asking it to convert a non value to DateTime. Item()
returns Object which can be tested easily before converting.
' System Type
If System.DBNull.Value.Equals(...)
您也可以使用DbReader.这仅适用于顺序索引,不适用于列名:
You can also the DbReader. This only works with the ordinal index, not a column name:
If myReader.IsDbNull(index) Then
基于此,您可以将函数作为共享类成员放在一起,也可以将其重新整理到Extensions中以测试DBNull并返回默认值:
Based on that, you can put together functions either as Shared class members or reworked into Extensions to test for DBNull and return a default value:
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转换器,您必须决定要返回什么.我更喜欢单独做.
For a DateTime converter, you'd have to decide what to return. I prefer to do those individually.
这篇关于如何检查DataReader值是否不为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!