C#使用SqlDataReader,我想从列中获取datetime值
我正在使用:C#使用SqlDataReader,我想从列中获取datetime值,c#,sql-server-2008,datetime,C#,Sql Server 2008,Datetime,我正在使用: string date1 = reader. GetDateTime(reader. GetOrdinal("firstMove"). ToString() 但是它抛出了一个异常,特别是当值为null时 试试下面的代码 string date1=reader["coloumn name"].tostring(); 如下所示使用,通过使用或函数检查是否为null if(string1 || string2 ||string3) 如果你告诉我们你得到了什么样的异常,那么你得到异
string date1 = reader. GetDateTime(reader. GetOrdinal("firstMove"). ToString()
但是它抛出了一个异常,特别是当值为null时 试试下面的代码
string date1=reader["coloumn name"].tostring();
如下所示使用,通过使用或函数检查是否为null
if(string1 || string2 ||string3)
如果你告诉我们你得到了什么样的异常,那么你得到异常的事实将更容易解决。可能的错误有:
DateTime
,因此GetDateTime
根本不起作用firstMove
根本不是有效的列名,因此您无法访问该列DateTime
我倾向于使用以下方法:
DateTime? d = reader["firstMove"] as DateTime?;
这很有效。你想要的是什么
DateTime? d = reader["firstMove"] as DateTime?;
string dstring = d.HasValue ? d.Value.ToString() : "";
或:
最好使用DateTime(或可为空的DateTime-DateTime?)而不是字符串来处理日期 如果要遵循此方法,可以使用扩展方法:
public static class IDataReaderExtensions
{
public static DateTime GetDateTimeOrMinValue(this IDataReader dr, int position)
{
if (dr.IsDBNull(position))
{
return DateTime.MinValue;
}
return dr.GetDateTime(position);
}
public static DateTime? GetDateTimeOrNull(this IDataReader dr, int position)
{
if (dr.IsDBNull(position))
{
return null;
}
return dr.GetDateTime(position);
}
}
用法:
DateTime dateA = reader.GetDateTimeOrMinValue(reader.GetOrdinal("firstMove"));
DateTime? dateB = reader.GetDateTimeOrNull(reader.GetOrdinal("firstMove"));
您甚至可以改进扩展方法,以便它可以接收列名并在内部查找序号位置
希望这有帮助,谢谢。现在,如果我使用if语句和elseif检查为null或空,我可以重复elseif多少次?基本上,我需要检查大约10个字符串的空响应。可能的重复代码甚至不会编译。你能展示一下简短但完整的程序吗?你到底得到了什么例外?谢谢你的尝试。这是a)不是答案,b)无效的C代码。这甚至不是有效的语法,除非
string1
、srting2
和string3
是有效的bool
值。这个“答案”在现在看来毫无帮助。你本可以把写评论的时间花在改进你的“答案”上,而不是。。。
DateTime dateA = reader.GetDateTimeOrMinValue(reader.GetOrdinal("firstMove"));
DateTime? dateB = reader.GetDateTimeOrNull(reader.GetOrdinal("firstMove"));