asp.net - 处理从数据读取器到子例程的空值
问题描述
我正在复制数据读取器检索到的记录(字符串和日期)并将它们插入数据库。我将这些值从数据读取器传递到名为 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
解决方案
在处理来自数据库的 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,...
推荐阅读
- node.js - 如何使用 Express-session Cookie 进行前端和后端分离的身份验证
- c++ - 如何将容器与智能 ptr 一起使用?
- javascript - 从嵌套对象中删除特定对象
- javascript - Javascript - 从内存缓存访问对象
- python - 消息大小如何影响 Kafka 中的消息传输速度?
- reactjs - auth0 不允许在 localhost 中使用 https
- android - 在颤动中调用Android布局时出错-活动/片段不同于线性/相对/框架布局
- android - 摆脱不了Android Studio原有的工具栏
- java - 为多种 xsd 类型指定一个适配器
- reactjs - 如何重新加载 localStorage 保存的 aws-amplify 身份验证?