我正在尝试使用C#将日期+时间插入Access数据库。时间字符串中包含毫秒,例如:
"2015-03-23 11:22:33.123"`
这是我的代码:
string strName = "somestring";
string strDate = "2015-03-23 11:22:33.123"
sql = @"insert into table_name ([name], [date]) values (@Name, @Date)";
using (OleDbCommand command = new OleDbCommand(sql))
{
command.Connection = openCon;
command.Parameters.AddWithValue("@Name", strName);
command.Parameters.AddWithValue("@Date", strDate ); // <-- error here
openCon.Open();
recordsAffected = command.ExecuteNonQuery();
openCon.Close();
}
我在遇到错误ExcuteNonQuery()
; 如果我删除日期时间字符串,则代码有效。
那么,如何将带有毫秒的datetime插入Access数据库中?
您正在混合使用DateTime和String。始终使用DateTime作为日期/时间值,或尽早转换为DateTime。因此:
string strDate = "2015-03-23 11:22:33.123";
DateTime datDate = DateTime.Parse(strDate);
// ...
// command.Parameters.AddWithValue("@Date", datDate ); // <-- error here
command.Parameters.Add("@Date",OleDbType.Date);
command.Parameters[0].Value = datDate; // <-- no error
请注意,尽管Access将正确存储该值,但它或VBA不会显示毫秒,而是将4/5舍入到秒。当然,如果您仅从C#应用程序中读取这些值,则这并不重要。
如在我的毫秒应用程序中插入的值所示,将正确插入该值:
DateTimeMs SortValue DateFull CDouble RoundSecSQL MsecSQL MsecVBA SecondDec SecondStd
23-03-2015 11:22:33 60438568953123 23-03-2015 11:22:33.123 42086,4739944792 42086,4739930556 123 123 33,123 33
23-03-2015 11:45:31 60438570330707 23-03-2015 11:45:30.707 42086,4899387384 42086,4899305556 707 707 30,707 31
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句