请问各位,C#中日期类型的变量为空,当保存到数据库中怎么样实现?

解决方案 »

  1.   

    DateTime.minValue,字段设置为允许null
      

  2.   

    一般做网站的话都是时间类型默认为getdate()
    一般不用的话就为null
      

  3.   

    用SqlDateTime.MinValue不行么?
      

  4.   


    如果是sqlserver,则不能使用DateTime.MinValue,因为这个值是0001年1月1日,而SqlServer最小只支持1900年1月1日。所以要用也应该用SqlDateTime.MinValue。
      

  5.   

    时间应该不能为空
    lz 可以先将时间转换成string
    在保存到数据库中
    不知道行不
      

  6.   

    你可以在数据库里面写 
      SQL Server 2000   日期那列的   默认值为  getdata()
      

  7.   

    你可以在数据库里面写 
      SQL Server 2000   日期那列的   默认值为  getdata()
      

  8.   

    我是将C#中一个日期类型的变量保存到sql server中,这个变量是允许为空,若为空,怎么样实现?C#中有SqlDateTime这个类吗?
      
      

  9.   


    我有说过把那个date的字段设置成null,这样的话DateTime.MinValue插入数据到sql里面就是null
      

  10.   

    .Net中的DateTime是struct,因此不能为空。
    解决的办法可以是用一个特殊的DateTime值来表示数据库中的null,比如DateTime.minValue,然后在写入数据库时判断一下,如果是DateTime.minValue则实际写入DBNull.Value。
    也可以用.Net提供的Nullable类型,用DateTime?代替DateTime,然后就可以使用DateTime? date = null这样的语句来赋空值。
    无论哪种方法都不是非常完美,但是没有办法。
      

  11.   


    DateTime是值类型,不存在Null不Null的问题。只有MinValue和MaxValue的东西。如果你直接将MinValue插入数据库,直接就exception了。你更不可能在程序中将null的值作为parameter的值传入,同样exception。这跟你db中的字段是否是allow null没关系。所以建议楼主还是用SqlDateTime.MinValue.Value来设置这个值,因为这样的话,今后你取出来后,就可以通过是不是MinValue来判断,当时我插入这条记录的时候,是否是默认该字段为空(我不关心这个日期)。如果你使用getdate,虽然能够默认往数据库插入数据,但当你再次取出的时候,你没法判断这个字段本应该是有值还是没值。下面的代码请楼主试试看:static void Main(string[] args)
    {
        try
        {
            SqlConnection conn = new SqlConnection("server=(local); database=test; Integrated Security=SSPI");
            conn.Open();
            SqlCommand command = new SqlCommand(
                @"INSERT INTO [Students] ([Name], [Age], [Birth]) VALUES (@name, @age, @birth)", conn);
            SqlParameter p1 = new SqlParameter("@name", "acqy");
            SqlParameter p2 = new SqlParameter("@age", 27);
            SqlParameter p3 = new SqlParameter("@birth", SqlDateTime.MinValue.Value);
            command.Parameters.Add(p1);
            command.Parameters.Add(p2);
            command.Parameters.Add(p3);
            command.ExecuteNonQuery();
            conn.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
      

  12.   

    BS一下自己,说了一堆,用DBNull可以
      

  13.   

    DateTime?类型...任何值类型都可以用泛型可空类型...
      

  14.   


    除非它实现了INullable接口