我有一个数据库,其中包含一个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值的正确配置是什么?
答案 0 :(得分:4)
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.");
}
}
答案 1 :(得分:0)
感谢您的回答,我终于按照建议将INSERT语句更改为SQLite格式了:
string empDob = dateDOB.Value.ToString("yyyy-MM-dd");
//I then inserted this string into the database with the column configured as a "DATE" datatype.
之后,我使用以下语句来读取日期并将其格式化为可用字符串,并且它工作得很漂亮:
DateTime dateOfBirthEmp = DateTime.Parse(readList["dob"].ToString());
lblEmpDob.Text = dateOfBirthEmp.ToString("d");
我真的很感激帮助。
答案 2 :(得分:0)
为什么要转换2次?
如果SQLite中有Date列,提供者可以为您管理。 您可以将插入指定为DateTime并读取为DateTime。