有时我们从数据库中获取我们想要的数据时,难免会遇到取出的数据为空( C#中用DBNull这种类型表示)的情况,如果直接使用强制转换,则会抛出异常。
例如:
String strSQL = string.Format("select SUM(point) from video_userconsume where userid='{0}' and roomsession={1} and state=3 ", Session["userid"], roomsession);
decimal giftPoints = (decimal)SqlHelper.ExecuteScalar(BasePage.GetConnectString(), CommandType.Text, strSQL);
正确的处理方法如下:
String strSQL = string.Format("select SUM(point) from video_userconsume where userid='{0}' and roomsession={1} and state=3 ", Session["userid"], roomsession);
Object o = SqlHelper.ExecuteScalar(BasePage.GetConnectString(), CommandType.Text, strSQL); decimal giftPoints =0;
//使用is 关键字判断取出的对象是否为DBNull类型
if (o is DBNull)
giftPoints =0;
else
giftPoints = (decimal)o;
if (o is DBNull)
giftPoints =0;
else
giftPoints = (decimal)o;
本文介绍了一种在C#中处理从数据库查询得到的DBNull值的方法。通过使用is关键字判断对象类型并设置默认值,避免了因直接转换DBNull引发的异常。
5906

被折叠的 条评论
为什么被折叠?



