C#中关于DBNULL的解释


本文摘自PHP中文网,作者黄舟,侵删。

1 概述

如下例子,你觉得有什么问题?如你能很快的找出问题,并且解决它,那么你可以跳过本篇文章,谢谢~~。

1

2

3

4

5

6

7

8

9

1 List<Base_Employee> ltPI = new List<Base_Employee>();

2 DataTable dt = GetBase_UserInfoToDataTable();

3 for (int i = 0; i < dt.Rows.Count; i++)

4    {

5          Base_Employee base_Employee= new Base_Employee();

6          base_Employee.EmployeeId= dt.Rows[i]["EmployeeId"].ToString();//EmployeeId为string类型

7          base_Employee.Age =(int)dt.Rows[i]["Age"];//Age为int类型

8          base_Employee.GraduationDate = (DateTime)dt.Rows[i]["GraduationDate"];//GraduationDate 为DateTime类型

9    }

想一分钟,OK,如果没想出来,可以往下看,下图标注处即为问题处。

ok,本篇文章就是来解决该问题的。也就是接下来要与大家分享的System.DBNULL类型

2 内容分享

2.1 在.NET中的,常用的基本数据类型

int,string,char等是大家比较熟悉的基本数据类型,但是大部分人都应该对System.DBNull比较陌生,然而,它又是解决如上问题的一大思路。

2.2 SqlServer中的常用数据类型

varchar,nvarchar,int,bit,decimal,datetime等,基本在与.net中的数据类型一一对应(varchar和nvarchar均对应.net中的string类型)

2.3 SqlServer中的常用数据类型的初始值

在.net中,当我们定义一个变量时,如果没给其赋初始值,那么系统会默认初始值,如int 类型默认为0,string类型默认为string.Empty,一般情况,不同类型的默认初始值是不同的;但是,在SqlServer中,几乎所有变量类型的初始值为NULL,也就要么为用户自定义的值,要么为系统默认的值NUL。问题的关键就在这,以int类型为例,当在数据库中,我们没有给INT赋值时,其默认值为NULL,当把这个值赋给.net中的整形变量时,就会引发异常。

2.4 System.DBNull是什么?

DBNull是一个类,继承Object,其实例为DBNull.Value,相当于数据中NULL值。

2.5 为什么 DBNull可以表示其他数据类型?

在数据库中,数据存储以object来存储的。

2.6 如何解决如上问题

加条件判断

可以用string类型是否为空,或DBNull是否等于NULL来判断


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

1 List<Base_Employee> ltPI = new List<Base_Employee>();

2 DataTable dt = GetBase_UserInfoToDataTable();

3 for (int i = 0; i < dt.Rows.Count; i++)

4    {

5          Base_Employee base_Employee= new Base_Employee();

6          base_Employee.EmployeeId= dt.Rows[i]["EmployeeId"].ToString();//EmployeeId为string类型

7          //base_Employee.Age =(int)dt.Rows[i]["Age"];//Age为int类型

8           if (dt.Rows[i]["Age"]!=System.DBNull.Value)

9                 {

10                     base_Employee.Age = int.Parse(dt.Rows[i]["Age"].ToString());

11                     //base_Employee.Age = (int)dt.Rows[i]["Age"];//拆箱

12                     //base_Employee.Age =Convert.ToInt16( dt.Rows[i]["Age"]);

13                 }

14          //base_Employee.GraduationDate = (DateTime)dt.Rows[i]["GraduationDate"];//GraduationDate 为DateTime类型

15         if (dt.Rows[i]["GraduationDate"].ToString()!="")

16                 {

17                     base_Employee.GraduationDate = Convert.ToDateTime(dt.Rows[i]["GraduationDate"]);

18                     base_Employee.GraduationDate = (DateTime)dt.Rows[i]["GraduationDate"];

19                 }

20    }

以上就是C#中关于DBNULL的解释的详细内容!

相关阅读 >>

文件事物管理transactional file manager的实例详解

.net安装framework出现报错的处理教程

解析.net垃圾回收(gc)原理

c#接口的问题的解决办法详解

c#开发中遇到的问题分享

基于.net平台常用的框架整理的详细介绍

c#通过kd树进行距离最近点的查找的实例分析

分享n种.net获取当前路径的的实例

比较.net中接口与类

.net页面局部更新引发的思考

更多相关阅读请进入《csharp》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...