字符串未被识别为有效的日期时间,源日期为0000-00-00:00:000

hmtdttj4  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(454)

更新
显然这不是由 0000-00-00 00:00:000 ,当值为 2016-04-21 00:00:00.000 知道原因是什么吗?
我有一个vsc程序,它将从mssql中选择,然后在mysql数据库中插入/重复更新。我有一行日期时间是 NULL ,我的mssql查询和结果是:
查询

  1. SELECT UserID,LastPasswordDate,
  2. CASE WHEN LastPasswordDate IS NULL THEN '0000-00-00 00:00:00:000'
  3. ELSE convert(varchar, LastPasswordDate, 121) END as LastPasswordDate2 from users
  4. order by LastPasswordDate

结果

c代码

  1. string LastPasswordDate = row["LastPasswordDate"].ToString(); // Or
  2. //DateTime LastPasswordDate = DateTime.ParseExact(row["LastPasswordDate"].ToString(), "yyyy-MM-dd HH:mm:ss:fff", null);
  3. insertUserCommand.Parameters.AddWithValue("@LastPasswordDate", LastPasswordDate);
  4. insertUserCommand.ExecuteNonQuery();
  5. insertUserCommand.Parameters.Clear();
  6. tran.Commit();

我试着使用c#转换,但得到的错误信息与前面提到的标题相同

amrnrhlw

amrnrhlw1#

问题是,用于检查的字符串“0000-00-00:00:00:000”无法在代码中转换为有效的日期时间,即使它可以像这样保存在数据库中。最好的解决方案是在数据库中设置一个默认值null并查找它

fhity93d

fhity93d2#

你应该知道的第一件事是 datetime mysql中的数据类型的最小值为 1000-01-01 00:00:00.000 ,不是 0000-00-00 00:00:00.000 当对无效日期使用日期时间转换时,用作“零”值显示。第二,市场 DateTime.MinValue 最小值为 0001-01-01 00:00:00.000 ,不适合与前面提到的mysql的“零值”进行转换。
如果mysql db中的目标列具有nullable datetime 数据类型,应该使用 TryParseExact() 使用 DBNull.Value 对于无法分析“零”日期时分配空值:

  1. DateTime date;
  2. DateTime? LastPasswordDate;
  3. if (DateTime.TryParseExact(row["LastPasswordDate"].ToString(), out date))
  4. {
  5. LastPasswordDate = date;
  6. }
  7. else
  8. {
  9. LastPasswordDate = null;
  10. }
  11. insertUserCommand.Parameters.AddWithValue("@LastPasswordDate", (object)LastPasswordDate ?? DBNull.Value);
  12. insertUserCommand.ExecuteNonQuery();

但在我看来,最好从t-sql查询中返回空值并用 Convert.IsDBNull() ,然后使用 DBNull.Value 对于将空值赋给数据库列:

  1. DateTime? LastPasswordDate = !Convert.IsDBNull(row["LastPasswordDate"]) ? DateTime.ParseExact(row["LastPasswordDate"].ToString(), "yyyy-MM-dd HH:mm:ss:fff", null) : null;
  2. insertUserCommand.Parameters.AddWithValue("@LastPasswordDate", (object)LastPasswordDate ?? DBNull.Value);
  3. insertUserCommand.ExecuteNonQuery();
展开查看全部
whlutmcx

whlutmcx3#

在.net中,datetime.minvalue是1/1/0001 12:00:00 am,因此0000-00-00:00:00超出了有效的datetime值的范围。
请参见datetime.minvalue

相关问题