Analysis of the difference between null and DBNull

Source: Internet
Author: User
Tags first row

Test Preparation:

1. Create a new table

CREATE TABLE ' CACB ' (
' CA ' varchar (255) DEFAULT NULL,
' CB ' varchar (255) DEFAULT NULL
) Engine=innodb DEFAULT Charset=utf8;

2. Create a new console project with the main function implemented as follows:

#region Mysql DBNull Test
String con = "server=localhost; User id=root;database=mytest;password=my88888;persist security Info=true;charset=utf8; ";

BOOL FLG = NULL is Object;//false
BOOL Fdb = DBNull.Value is Object;//true

String sql = "SELECT * from CACB limit 1, 1;";
using (mysqlconnection mc=new mysqlconnection (Con))
{
Mc. Open ();
using (Mysqlcommand com=new Mysqlcommand (SQL,MC))
{
var result= com. ExecuteScalar ();
if (Result==dbnull.value)
{
Console.WriteLine ("This certainty is the database empty");
}
if (result==null)
{
Console.WriteLine ("Here is null.");
}
}
}
#endregion

3. Conclusion: DBNull is for those data that are queried for null, inheriting object,null is a type of data inside. NET that does not inherit object, and plainly, DBNull is the default null value for the database, and NULL is the default value of. Net. So Row[column]. The ToString () is never written in ToString where NullReferenceException occurs.

It is important to note that the ExecuteScalar rule is to return the first column, the first row of data. If there is a first row, but the first column is empty, then the return is DBNull. If there is no line, then ExecuteScalar returns NULL, if the first row of the first column is not empty, then executescalar directly corresponds to the value of dotnet.

Therefore, when we query the results of the data, we should pay attention to directly using dbresult==null as a condition to judge is prone to problems.

can refer to the exploration of the predecessors:

    1. http://blog.csdn.net/cmalaya/article/details/7222621

    2. Http://www.cnblogs.com/chen-fan/articles/2171399.html



Analysis of the difference between null and DBNull

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.