首页 > 解决方案 > 处理从数据读取器到子例程的空值

问题描述

我正在复制数据读取器检索到的记录(字符串和日期)并将它们插入数据库。我将这些值从数据读取器传递到名为 InsertNewHearings() 的子例程。我的问题是 dr 检索到的值通常为 NULL 并导致错误“从类型 'DBNull' 转换为类型 'Date' 无效”

Using con
  con.Open()
  dr = cmd.ExecuteReader()
  While dr.Read()
     Dim LastUserID As String = lblLastUserID.Text
     UserID = GetRandomUser(LastUserID)
     Dim strAssigned_Date As Date = DateTime.Now()
     Dim strUpload_Date As Date = DateTime.Now()
     InsertNewHearings(dr("Borrower_Number"), 
     dr("Review_Doc_Date"), dr("Review_Type"), dr("PCAID"), 
     dr("Day65_Notice_Date"), dr("Hearing_Image_Date"), 
     dr("Additional_Docs_Date"), dr("Request_Postmark_Date"), 
     dr("Timeliness_Hearing_Request"), strUpload_Date, UserID, 
     strAssigned_Date)
   End While
  End Using

Sub InsertNewHearings(ByVal Borrower_Number As String, ByVal 
Review_Doc_Date As Date, ByVal Review_Type As String, ByVal PCAID As 
String, ByVal Day65_Notice_Date As Date, _
ByVal Hearing_Image_Date As Date, Additional_Docs_Date As Date, 
Request_Postmark_Date As Date, ByVal Timeliness_Hearing_Request As String, 
strUpload_Date As Date, UserID As String, strAssigned_Date As Date)
 'Inserts record into database
End Sub       

标签: asp.netvb.net

解决方案


在处理来自数据库的 NULL 日期时,VB.NET 日期有点奇怪。首先,要处理从数据库中将具有 NULL 值的日期读取到您的 VB.NET Date 变量中:

Dim myDate As Date = If(dr("MyDate") Is DBNull.Value, Nothing, dr("MyDate")) 

请注意,将 Date 类型设置为 Nothing 会为其提供 #12:00:00# 的值(Date 数据类型的最小值),而不是空对象中的 Nothing。这意味着您检查 Nothing 的日期以将 NULL 发送到数据库,如下所示:

cmd.Parameters("@MyDate").Value = If(.myDate = Nothing, DBNull.Value, .myDate)

请注意,我们使用If(.myDate Is Nothing,...


推荐阅读