c#SQL Server:DATETIME数据类型 [英] c# SQL Server : DATETIME datatype
问题描述
我正在写一个单元测试,它将一个 DateTime
参数的对象存储到一个 DATETIME2
SQL Server数据库列。然后我创建一个临时的 DateTime
对象调用 new_date_time
并将该值设置为 DateTime.Now
。
I am writing a unit test which stores an object with a DateTime
parameter into a DATETIME2
SQL Server database column. I then create a temporary DateTime
object called new_date_time
and set that value to DateTime.Now
.
然后, new_date_time
值用于更新以前的值和SQL查询这样做成功完成。
The new_date_time
value is then used to update the previous value and the SQL query to do this completes successfully.
当从数据库重新读取对象时,我收到正确的 datetime
值日期/小时/分钟,但 .Ticks
的值与 new_date_time
变量不同。点击
属性。从read函数返回的值返回$ code> .Ticks 属性的最后4位数字为零。
When re-reading the object back from the database I receive the correct datetime
values for days/hours/minutes but the .Ticks
value is different from the new_date_time
variables .Ticks
property. The value returned from the read call returns the last 4 digits of the .Ticks
property as zeros.
为什么这个四舍五入使我的 Assert.AreEqual
失败? :
Why is this rounding occurring making my Assert.AreEqual
fail?? :)
谢谢
推荐答案
我想你正在使用 Parameters.AddWithValue
将日期写入Sql Server时。从 MSDN 推断出CLR类型 DateTime
是 SqlDbType.DateTime
和不 SqlDbType.DateTime2
,所以在将日期写入数据库时,精度会丢失。
I guess you are using Parameters.AddWithValue
when writing the date to Sql Server. From MSDN the inferred type of a CLR DateTime
is SqlDbType.DateTime
and not SqlDbType.DateTime2
so the precision is being lost when writing your date to the database.
将类型显式设置为 datetime2
将解决问题。例如:
Explicitly setting the type to datetime2
will solve the issue. For example:
command.Parameters.AddWithValue("@now", DateTime.Now).SqlDbType =
SqlDbType.DateTime2;
修改
@marc_s 对他的评论很好:
你应该阅读(并拥抱!)我们可以停止使用AddWithValue()吗?
这些类型的问题从咬你,你可以习惯使用添加
方法在参数集合,采取 SqlDbType
在某些重载,然后设置值
属性,而不是使用 AddWithValue
方法:
To avoid these kind of issues from biting you, you could get into the habit of using the Add
method on the parameters collection which takes the SqlDbType
in some overloads and then set the Value
property on that rather than using the AddWithValue
method:
command.Parameters.Add("@now", SqlDbType.DateTime2).Value = DateTime.Now;
这篇关于c#SQL Server:DATETIME数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!