How to assign the null value, null and "" to the datetime type in the C # and SQL Server databases

Source: Internet
Author: User
Tags date1

 

Today, when you assign the datetime type data in the database to the datetime type variable in C #, a problem occurs, that is, the datetime data in the database has a null value.

C # by default, null cannot be assigned to the datetime variable, but nullable type datetime can be used. You only need to add? Number, such:

Datetime? X;

X can be assigned a null value.

However, changing from the datetime type of the database to the datetime type of C # requires convert. todatetime (). If the datetime data in the database is null, this method cannot be used.

So I added an if statement:

If (row ["date1"])! = NULL)

However, this If statement is invalid.

Row ["date1"]. tostring ()! = NULL

You still cannot determine whether the datetime-type column date1 in the database is null.

Later changed to row ["date1"]. tostring ()! = "" Can finally be judged. Complete statement:

Datetime? X;

If (row ["date1"]. tostring ()! = "")

X = convert. todatetime (["date1"]);

Else

X = NULL;

Note that in the end, X can only be null, rather than "" as in the original database data "". Because X is declared as a nullable <datetime> type variable.

In this way, if X is saved to the database, the database is shown as 1900-1-1.

The difference between null and "" in C # is that the former does not point to any string object, while the latter is a string object with a length of 0 and allocates memory space for it.

But I just tried it. No matter whether "" or null is stored in the database, it is-1-1. If you want to be null in the database, you can choose when X is null or, do not store related columns in the database.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.