C#
定石4: NULL値ハンドリングの違い
出典: C# DataReader vs DataAdapter — メモリ消費と性能の使い分け(業務SE 判断軸) — 定石4: NULL値ハンドリングの違い
// ❌ NG: DataReader.GetInt32()にNULLが来ると例外
int id = reader.GetInt32(0); // NULL行でSqlNullValueException
// ✅ OK: DataReaderはIsDBNullで先にチェック
int? id = reader.IsDBNull(0)? (int?)null : reader.GetInt32(0);
// ✅ OK: DataAdapter / DataTableはField<int?>で受ける
int? id = dt.Rows[0].Field<int?>("id"); // NULLはnullで返る
// ❌ NG: Field<int>だとNULL行で例外(StrongTypingExceptionまたはInvalidCastException)
int id2 = dt.Rows[0].Field<int>("id");
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「定石4: NULL値ハンドリングの違い」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
4 件// ✅定石1: SqlDataReaderでストリーム読み取り using (var conn = new SqlConnection(connStr)) using (var cmd = new SqlCommand("SELECT id, name, amount FROM order_log WHERE status = @s", conn)) {未収録
定石1: DataReaderの最小コード—ストリーム読み取り
#1804e9186ec0
// ✅定石2: SqlDataAdapterでDataTableにバルクロード DataTable dt = new DataTable(); using (var conn = new SqlConnection(connStr))未収録
定石2: DataAdapterの最小コード— DataTableバルクロード
#b20554e37854
// ✅定石3:メモリ・実行時間の実測比較 const string sql = "SELECT id, name, memo, amount, created_at FROM big_log"; // --- DataAdapter版---
▶ 実行可
定石3:メモリ消費の実測比較— Stopwatch + GC.GetTotalMemory
#8e4ad96d6711
// ✅定石4-b: DataReader用NULL安全ヘルパー public static class ReaderEx { public static int? GetIntOrNull(this SqlDataReader r, int i)未収録
定石4: NULL値ハンドリングの違い
#e782c17c1e04
