DBNull异常处理

 

今天为了偷懒不想写数据库访问操作类,而直接使用DotNet的LINQ to SQL类或者是 数据集模板,在查询数据时出现 表“Products”中列“ShipRegion”的值为 DBNull 的异常,使用 order.shipRegion = System.DBNull.Value.Equals(od.ShipRegion) ? “” : od.ShipRegion; 和 order.shipRegion = Convert.IsDBNull(od.ShipRegion) ? “” : od.ShipRegion; 均不凑效依然抛出(表“Products”中列“ShipRegion”的值为 DBNull)的异常信息,十分郁闷.然后上网搜索一番,试过N种方案,问题依然存在.因为在代码中加入了捕获异常,所以调试时直接显示该异常信息.很想把数据集删除然后手工写数据库访问操作类,但又不死心啊,因为从来就是手工写,而第一次使用就出问题,心里太不爽了.为了能在调试中找到问题代码,所以将try catch代码删除后进行调试,结果发现这个异常信息在是 数据集 类的设计代码中抛出的,将抛出异常代码删除改为return “”(因为数据库中的值是Null,而显示给客户的信息就应该为空串,所以就直接返回空串),再调试程序时,问题得以解决.

同时悟出try catch在某些情况下会隐藏真实的问题.以下是我遇到問題中的部分代碼

文件名:NorthwindData.designer.cs

[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]

            public string ShipRegion {

                get {

                    try {

                        return ((string)(this[this.tableProducts.QuantityPerUnitColumn]));

                    }

                    catch (global::System.InvalidCastException e) {

                        throw new global::System.Data.StrongTypingException("表“Orders”中列“ShipRegion”的值为 DBNull。", e);

                    }

                }

                set {

                    this[this.tableOrders.ShipRegionColumn] = value;

                }

            }

修改為

[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]

            public string ShipRegion {

                get {

                    try {

                        return ((string)(this[this.tableProducts.QuantityPerUnitColumn]));

                    }

                    catch  {

                        retrun “”;

                    }

                }

                set {

                    this[this.tableOrders.ShipRegionColumn] = value;

                }

            }

[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]

            public string ShipRegion {

                get {

                    try {

                        return ((string)(System.DBNull.Value.Equals( (this[this.tableOrders.ShipRegionColumn])) ? "": (this[this.tableOrders.ShipRegionColumn])));

                    }

                    catch (global::System.InvalidCastException e) {

                        throw new global::System.Data.StrongTypingException("表“Orders”中列“ShipRegion”的值为 DBNull。", e);

                    }

                }

                set {

                    this[this.tableOrders.ShipRegionColumn] = value;

                }

            }

 

若不想用以上方法,那就使用 DBNull.Value.Equals() 来判断是否为DBNull吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

meiarne

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值