使用SqlDataReader的C#我想从列中获取日期时间值

问题描述 投票:-1回答:4

我正在使用 :

string date1 = reader. GetDateTime(reader. GetOrdinal("firstMove"). ToString() 

但它正在抛出异常,特别是如果值为null ....

c# sql-server-2008 datetime
4个回答
0
投票

请尝试以下代码。

string date1=reader["coloumn name"].tostring();

0
投票

如果你告诉我们你得到的是什么样的例外,你获得例外的事实会更容易解决。可能的错误是:

  1. 专栏不是qazxsw poi,这个qazxsw poi根本不起作用
  2. DateTime根本不是有效的列名,因此您无法访问该列

假设列真的存在并且类型为GetDateTime,我倾向于使用以下内容:

firstMove

这非常有效。你想要的是什么

DateTime

要么:

DateTime? d = reader["firstMove"] as DateTime?;

0
投票

对你来说,使用DateTime(或可以为空的DateTime - DateTime?)而不是字符串来处理日期会更好。

如果要使用此方法,可以使用扩展方法:

DateTime? d = reader["firstMove"] as DateTime?;
string dstring = d.HasValue ? d.Value.ToString() : "";

用法:

string date1 = !reader.IsDBNull(reader.GetOrdinal("firstMove")) ? reader.GetDateTime(reader.GetOrdinal("firstMove").ToString() : String.Empty;

您甚至可以改进扩展方法,因此它可以接收列名并在内部查找序号位置。

希望这可以帮助,


-2
投票

使用如下所示,通过使用或函数来检查null是否为null。

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.