私はいくつかの興味深い状況に直面しました。DB (ASP.net) からフィールドの値を入力する次のコードがあります。
SqlConnection connect =
new SqlConnection(
@"conn-string");
SqlCommand toDo = new SqlCommand(InfoQuery, connect);
toDo.CommandTimeout = 6000;
connect.Open();
using (SqlDataReader reader = toDo.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
///......retrieving some fields in the same way as below
foo = reader.SafeGetString(7);
int temp = reader.SafeGetInt32(8);
///......retrieving again
}
}
connect.close()
接続が確立され、すべてのパラメータが正しい。SQL Server Management Studio では、コマンドに関連付けられたクエリはtoDo
完璧に機能します。プログラムでは、実行時にすべてのフィールドのtemp
値 (temp を除く) が取得され、設定されます。しかし、一時値を読み取ると、次の例外が発生します。
データが存在しない場合の読み取りの試みは無効です。
そして、ここに私の拡張メソッドがあります:
public static class ExtentionMethods
{
public static string SafeGetString(this SqlDataReader reader, int colIndex)
{
if (!reader.IsDBNull(colIndex))
return reader.GetString(colIndex);
return "NULL VALUE";
}
public static int SafeGetInt32(this SqlDataReader reader, int colIndex)
{
if (!reader.IsDBNull(colIndex))
return reader.GetInt32(colIndex);
return -1;
}
public static DateTime SafeGetDateTime(this SqlDataReader reader, int colIndex)
{
if (!reader.IsDBNull(colIndex))
{
try
{
}
catch
{
return new DateTime(1800, 1, 1);
}
}
return new DateTime(1800, 1, 1);
}
}
クエリ:
SELECT TOP 1000 [ID0]
,[Id1]
,[Id2]
,Id1+Id2+'0' AS BC
,[Id3]
,[Id4]
,[Id5]
,CAST([Date] AS nvarchar(max))
,[int]
,[Id7]
,[Id8]
,IsNull(foo,'dsf')+' '+IsNull(bar,'dsf')+', '
+IsNull(fgm,'fggf')+', fgfggf '+IsNull(gfgf,'gfgf')+
','+dfsdfsdsf+', '+dsffddf AS dsadsa
,[fg]
,[fds]
FROM tbl
inner join tbl1 on tbl1.ID=ID1
inner join tbl2 on tbl2.ID=ID2
WHERE Id4=12
問題は何ですか?