我有一个带有数据表的数据库,其中包括 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.");
}
}
关于c# - 从数据库中读取 SQLite DateTime 值并将其分配给 C# 字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42630427/