Taking a NULL value from the database and assigning a Date variable

The stored procedure returns information about the user record, including a column with a zero column of date and time for their last entry date. Which one is the best choice when considering the possibility of NULL values ​​when trying to assign a .Net date variable?

    Try
        _LastLogin = CDate(DT.Rows(0)("LastLogin"))
    Catch ex As InvalidCastException
        _LastLogin = Nothing
    End Try

or

    If DT.Rows(0)("LastLogin") Is DBNull.Value Then
        _LastLogin = Nothing
    Else
        _LastLogin = CDate(DT.Rows(0)("LastLogin"))
    End If

Change . I also forgot about the possibility of using TryParse

    If Not Date.TryParse(DT.Rows(0)("LastLogin").ToString, _LastLogin) Then
        _LastLogin = Nothing
    End If

What is the preferred method for processing possible values NULLfrom a database? Is there a better way than the three listed?

Change # 2 . I noticed that the method TryParsedoes not work well when trying to assign a type Nullable.

+3
source share
5

. , , . , . , , DBNull , .

, , , ( , , ).

+6

- , ( , LastLogin NULL ).

(. " " ).

+2

FixDBNull:

Public Class FixDBNull(Of ItemType)    
    Public Shared Function Convert(ByVal data As Object) As ItemType
        If data IsNot System.DBNull.Value Then
            Dim obj As ItemType = Nothing

            Try
               obj = CType(data, ItemType)    
            Catch ex As Exception
                'do something with the conversion error
            End Try

            Return obj
        Else
            Return Nothing
        End If

End Function
End Class

:

_LastLogin = FixDBNull(Of date).Convert( DT.Rows(0)("LastLogin"))

, .

+2

VB.net, Nullable (of Date)

:

dim theDate as nullable(of Date)

    If theDate.HasValue Then
      'you can proceed
    Else
      'you must assign with DBNull.value
    End If

The database can also affect what you can do. MS Access will give out some dates. I ended up getting the above, but usually prefer to save dates as strings in Access. It just makes less hassle along the way.

+1
source

I would use TryCastone that would look something like this:

_LastLogin = TryCast(DT.Rows(0)("LastLogin"), Date?)
0
source

Source: https://habr.com/ru/post/1704596/


All Articles