【发布时间】:2011-07-01 19:09:02
【问题描述】:
我在将 DateTime 值作为 DbParameter 传递给查询时遇到问题。似乎 DateTime 值的时间部分被剥离了。
这是一个 C# 示例代码:
DbProviderFactory _factory = OleDbFactory.Instance;
DbCommand cmd = _factory.CreateCommand();
cmd.CommandText = "INSERT INTO SomeTable (SomeDateField) VALUES (?)";
DbParameter p = _factory.CreateParameter();
p.ParameterName = ""; // Not necessary
p.Value = DateTime.Now; // assume Time != 00:00:00
p.DbType = DbType.Date; // DateTime and DateTime2 don't work
cmd.Parameters.Add(p);
我的问题是 Date 参数似乎没有通过它的时间部分到达 Access 并且 SomeDateField 总是将 00:00:00 作为时间。
我不想做这样的事情:
cmd.CommandText = "INSERT INTO SomeTable (SomeDateField) VALUES (#" + aDateTimeString + "#)";
【问题讨论】:
-
数据库表中列的数据类型是什么?另外
DbType.DateTime不起作用是什么意思? -
当我使用 DbType.DateTime 和 DbType.DateTime2 时,我在执行命令时收到“条件表达式中的数据类型不匹配”异常。
-
我使用Access作为后端,所以列数据类型是Date,但它相当于.NET中的DateTime,它也可以包含时间部分。
-
以下答案表明 DateTime 值中的毫秒数可能是一个问题:stackoverflow.com/a/29207251/13087 因此,如果您想避免使用特定于提供程序的数据类型(假设此精度足以满足您的用例)。
标签: c# datetime oledbparameter