【问题标题】:FormatException was not managed on DateTimeFormatException 未在 DateTime 上进行管理
【发布时间】:2016-09-09 18:16:05
【问题描述】:

我遇到了DateTime 的问题,特别是我要从sqlite 的表中读取所有记录,现在列名是StartDate 并且是DateTime 格式。这就是我尝试读取数据的方式:

dbCon.Open();
string sql = "SELECT * FROM " + table_name;
SQLiteCommand command = new SQLiteCommand(sql, dbCon);
var reader = command.ExecuteReader();

while (reader.Read())
{
      Console.WriteLine(reader["StartDate"]);
      ..

但我明白了:

FormatException 未被管理

记录的日期是这种格式 2016 年 5 月 3 日

【问题讨论】:

  • 你用过调试器吗? reader["StartDate"] 真的是 DateTime 吗?你从哪里得到异常?在command.ExecuteReader()while (reader.Read())Console.WriteLine(reader["StartDate"])
  • 我在 Console.WriteLine 上遇到异常。是的,在数据​​库表中是一个DateTime
  • 在该行设置断点并在调试器中尝试((DateTime)reader["StartDate"]).ToString()。你有同样的例外吗?一般来说,DateTime 没有格式,因为它没有格式。它只是有一个价值。
  • 使用即时窗口或将鼠标悬停在变量上,然后在写入之前及时查看 reader["StartDate"] 的内容
  • 对这个问题的有趣评论stackoverflow.com/questions/33787426/…

标签: c# sqlite datetime


【解决方案1】:

好的,经过多次尝试,我找到了解决方案,特别是SQLite似乎无法自动识别连接,为了解决这个问题,我们需要像这样声明连接源:

source=<source to db file>;version=3;new=False;datetimeformat=CurrentCulture

之后可以读取日期如下:

Console.WriteLine(reader["StartDate"]);

没有返回错误,希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多