SQLReaderからINTからヌル可能な結果を安全にキャストする方法は?
-
28-10-2019 - |
質問
null値を含むテーブルがあり、sqldatareaderを使用してテーブルからデータを取得する必要があります。 dbnullをintに安全にキャストできる方法を理解できません。
私は現時点でこの方法でそれをやっています:
...
reader = command.ExecuteReader();
while (reader.Read()) {
int y = (reader["PublicationYear"] != null) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
...
しかし、取得します Object cannot be cast from DBNull to other types.
PublicationYearがnullの場合。
どうすれば価値を安全に取得できますか?
ありがとう。
解決
比較する必要があります reader["PublicationYear"]
に DBNull.Value
, 、 いいえ null
.
他のヒント
DBNull
と同じではありません null
. 。代わりにこのようなことを試す必要があります:
int y = (reader["PublicationYear"] != DBNull.Value) ? ...
int ord = reader.GetOrdinal("PublicationYear");
int y = reader.IsDBNull(ord) ? 0 : reader.GetInt32(ord);
または、あるいは:
object obj = reader["PublicationYear"];
int y = Convert.IsDBNull(obj) ? 0 : (int)obj;
返される値がタイプであるかどうかを明示的に確認する必要があります DBNull
while (reader.Read()) {
int y = (!reader["PublicationYear"] is DBNull) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
実際、この比較は値だけでなくタイプで行うことができます。
reader["PublicationYear"] != DBNull.Value
要するに、あなたは期待することができます DBNull
null自体ではなく、データベースからヌルに対して返される。
別の方法として、次のことを行うことができます。 dbnullを0に変換しているときに、selectを実行する手順を変更します。 null値の場合、選択自体がゼロを返すようにします。
アイデアを示すためのスニペット
SELECT ...
,ISNULL (PublicationYear, 0) as PublicationYear
...
FROM sometable
これの利点は、コードに追加のチェックが必要ないことです。
変化する
reader["PublicationYear"] != null
に
reader["PublicationYear"] != DBNull.Value
それがエラーです: (reader["PublicationYear"] != null)
dbnull.valueをテストする必要があります。
テストを変更します (reader["PublicationYear"] != null)
に (reader["PublicationYear"] != DBNull.Value)
.
データベースnull値は、dbnull.valueと比較する必要があります
reader = command.ExecuteReader();
while (reader.Read()) {
int y = (reader["PublicationYear"] != DBNull.Value) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}