将dbnull转换为字符串。在数据库中记录dbnull.value而不是Nothing [英] Convert dbnull to string. Record dbnull.value in database instead of Nothing
问题描述
我在vb.net中有一个insertRecord函数,该函数使用参数查询。如果没有给出错误日期,则需要在数据库中插入dbnull.value而不是(无)。
I have an insertRecord function in vb.net that uses a parameter query. If there is no error date given, I need to insert dbnull.value into the db instead of ""(Nothing).
Dim strErrorDate2 As DateTime = Request.Form("dateOfErrorDatePicker2").ToString
.Add(New SqlParameter("@ErrorDate2", If(strErrorDate2 <> Nothing, strErrorDate2.Date, DBNull.Value)))
我一直在dbnull到字符串的转换错误中遇到错误。最初,它在初始化变量的地方有自己的if / else块,但无法弄清楚如何正确转换它。我可以尝试内联,但仍然需要进行转换或尝试其他操作。
I keep getting conversion errors on dbnull to string. Originally it had it's own if/else block where I initialized the variable, but I couldn't figure out how to convert it correctly. I tried the inline if, but I still need to do a conversion or try something else.
有什么想法吗?问题是,当我在数据库中插入空字符串或DateTime时,它会记录为最短的日期,例如1/1/1900。
Any ideas? The problem is that when I insert an empty string or DateTime into the database it records as a min possible date such as 1/1/1900.
编辑:无法推断一种常见的类型,假设为对象。那是我当前遇到的错误。
"Cannot infer a common type, 'object' assumed." That's the error I'm currently getting.
推荐答案
这是因为strErrorDate2.Date是DateTime,而System.DbNull.Value是宾语。直接将strErrorDate2强制转换为IF()中的对象,或者执行类似的操作
It's because strErrorDate2.Date is a DateTime and System.DbNull.Value is an object. Either Direct Cast strErrorDate2 to object in the IF() or do something like this
Dim oErrorDate2 as Object = System.DbNull.Value
If strErrorDate2 <> Nothing Then oErrorDate = strErrorDate2
.Add(New SqlParameter("@ErrorDate2",oErrorDate2))
这篇关于将dbnull转换为字符串。在数据库中记录dbnull.value而不是Nothing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!