来源:http://blog.csdn.net/beautifulsarah/article/details/54691670
DBNull.Value,, 适用于向数据库的表中插入空值。而 null,是指在程序中表示空引用。 或者对象为空。就是没有实例化。
row[column]的值为DBNull.Value的话,至少说明它是从数据库中取到值了,对应了数据库中的空值;但如果row[column]的值为null的话,说明没有从数据库中取到值。DBNull.Value是一个有着内存地址的具体类型的值,映射了数据库中的null值;而NULL则是空指向,不存在对应的内存地址。任何对象赋值为null后,内存就释放了。
转换方法:
heper类中:
/// <summary> /// 将null转换为DBNull.Value /// </summary> /// <param name="value"></param> /// <returns></returns> public object ToDbValue(object value) { if (value == null) { return DBNull.Value; } else { return value; } } /// <summary> /// 将DBNull.Value转换为null /// </summary> /// <param name="value"></param> /// <returns></returns> public object FromDbValue(object value) { if (value == DBNull.Value) { return null; } else { return value; } }
应用:
public List<DateJg> GetList(int ncpid, DateTime start, DateTime end) { var list = new List<DateJg>(); string sql = @"select * from v_yjdatealljg where yjxzqid=9 and ncpid =@ncpid and cjrq>=@start and cjrq<=@end order by cjrq,yjxzqid,ncpid"; var sqlparms = new SqlParameter[] { new SqlParameter("@ncpid",ncpid), new SqlParameter("@start",start.Date), new SqlParameter("@end",end.Date) }; var table = helper.ExecuteDataTable(sql, sqlparms); using (System.Data.IDataReader dataReader = table.CreateDataReader()) { while (dataReader.Read()) { list.Add(GetInfo(dataReader)); } } return list; } private DateJg GetInfo(IDataReader reader) { var info = new DateJg(); info.lsjg = (decimal?)helper.FromDbValue(reader["lsjg"]); info.ncpid = (int)helper.FromDbValue(reader["ncpid"]); info.ncpmc = (string)helper.FromDbValue(reader["ncpmc"]); info.pfjg = (decimal?)helper.FromDbValue(reader["pfjg"]); info.rq = (DateTime)helper.FromDbValue(reader["cjrq"]); info.ttjg = (decimal?)helper.FromDbValue(reader["ttjg"]); info.yjxzqid = (int)helper.FromDbValue(reader["yjxzqid"]); info.yjxzqname = (string)helper.FromDbValue(reader["yjxzqname"]); return info; }