有什么应对的DBNull的最好的方法 [英] What is the best way to deal with DBNull's

查看:184
本文介绍了有什么应对的DBNull的最好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我常常必须处理来自SqlDataAdapters返回数据行的问题。当我尝试使用一个对象来填充code是这样的:

I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this:

DataRow row = ds.Tables[0].Rows[0];
string value = (string)row;

什么是应对的DBNull在这种情况最好的方法。

What is the best way to deal with DBNull's in this type of situation.

推荐答案

可空类型是好的,但仅适用于不可为空开始与类型。

Nullable types are good, but only for types that are not nullable to begin with.

要做出一种可空追加一个问号的类型,例如:

To make a type "nullable" append a question mark to the type, for example:

int? value = 5;

我也建议你使用关键字,而不是铸造。您只能使用在可空类型为关键字,所以一定要确保你铸造的东西都已经可以为空(比如字符串),或者使用可空类型如上所述。其理由为,这是

I would also recommend using the "as" keyword instead of casting. You can only use the "as" keyword on nullable types, so make sure you're casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this is

  1. 如果一个类型是空的,则关键字返回如果某个值的DBNull
  2. 这是<一href="http://www.$c$cproject.com/Articles/8052/Type-casting-impact-over-execution-performance-in">ever-so-slightly比铸造虽然只在某些情况下的速度更快。这对自己是不是一个好足够的理由来使用,但是加上上面这是很有用的原因。
  1. If a type is nullable, the "as" keyword returns null if a value is DBNull.
  2. It's ever-so-slightly faster than casting though only in certain cases. This on its own is never a good enough reason to use as, but coupled with the reason above it's useful.

我建议你做这样的事情

DataRow row = ds.Tables[0].Rows[0];
string value = row as string;

在上述情况下,如果回来为的DBNull ,然后将成为,而不是抛出异常。请注意,如果您的数据库的查询更改列/类型的返回,使用将导致您的code,以静默失败并做出价值简单的,而不是当返回不正确的数据,因此建议您检查到位,以验证您的查询在其他的方式来保证数据的完整性为您$抛出适当的异常C $ CBase的演变。

In the case above, if row comes back as DBNull, then value will become null instead of throwing an exception. Be aware that if your DB query changes the columns/types being returned, using as will cause your code to silently fail and make values simple null instead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves.

这篇关于有什么应对的DBNull的最好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆