c# - 从数据库中读取 SQLite DateTime 值并将其分配给 C# 字符串变量

标签 c# sqlite datetime

我有一个带有数据表的数据库,其中包括 DateTime 列等。使用 SQL Server 时,我可以使用以下代码从数据库中读取 DateTime 值:

    SqlCommand getdate = new SqlCommand("SELECT * FROM EMPinfo WHERE id = @employeeId", connect);
                getdate.Parameters.AddWithValue("@employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
                getdate.Connection = connect;
                connect.Open();
                SqlDataReader readList = getdate.ExecuteReader(CommandBehavior.CloseConnection);
                while (readList.Read())
                {
                    lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");
                }

更改代码以使用 SQLite 运行后:

    SQLiteConnection connect = new SQLiteConnection(@"Data Source=quotevodata.db;");
                SQLiteCommand getlistname = new SQLiteCommand("SELECT * FROM EMPinfo WHERE id = @employeeId", connect);
                getlistname.Parameters.AddWithValue("@employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
                getlistname.Connection = connect;
                connect.Open();
                SQLiteDataReader readList = getlistname.ExecuteReader(CommandBehavior.CloseConnection);
                while (readList.Read())
                {
                     lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");

                }

我不断收到以下错误:“字符串未被识别为有效的日期时间。”

我尝试了不同的变量组合和声明,但没有成功。从 SQLite 数据库中读取 DateTime 值的正确配置是什么?

最佳答案

SQLite 没有内置的 DateTime 对象,而是将它们存储为 Text、Real 或 Int 值。

从你的错误中,你可以推断它输出为文本;根据 SQLite 文档,其格式应为“YYYY-MM-DD HH:MM:SS.SSS”

有多种方法可以将其解析为 DateTime 对象,但我将使用 RegEx:

public static DateTime ConvertToDateTime(string str)
{
    string pattern = @"(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})";
    if (Regex.IsMatch(str, pattern))
    {
        Match match = Regex.Match(str, pattern);
        int year = Convert.ToInt32(match.Groups[1].Value);
        int month = Convert.ToInt32(match.Groups[2].Value);
        int day = Convert.ToInt32(match.Groups[3].Value);
        int hour = Convert.ToInt32(match.Groups[4].Value);
        int minute = Convert.ToInt32(match.Groups[5].Value);
        int second = Convert.ToInt32(match.Groups[6].Value);
        int millisecond = Convert.ToInt32(match.Groups[7].Value);
        return new DateTime(year, month, day, hour, minute, second, millisecond);
    }
    else
    {
        throw new Exception("Unable to parse.");
    }
}

文档:http://www.sqlite.org/datatype3.html

关于c# - 从数据库中读取 SQLite DateTime 值并将其分配给 C# 字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42630427/

相关文章:

c# - 获取连接的 USB 设备列表

c# - 使用 RSACryptoServiceProvider 从 XML 导入 RSA 公钥将属性 PublicOnly 设置为 false

c# - 在运行时调整我的 WinForms 应用程序主窗体起始大小和位置的最安全方法是什么?

r - 将十进制日转换为 HH :MM

c# - DateTime 转换为 Unix Epoch 添加 Phantom Hour

c# - "stand alone"类文件如何工作?

sql - 需要一个专注于表组合的 SQL 语句,但条目始终具有唯一 ID

c - 从 sqlite 表中的行中删除重复元素

Android Eclipse DDMS - 无法从 Root设备中提取文件

javascript - 是否有任何库可以识别任何格式的日期?