简体   繁体   English

使用C#DataReader时的时间戳格式不同

[英]Different format for timestamp when using c# datareader

I'm reading a timestamp from a mysql table using an OdbcDataReader . 我正在使用OdbcDataReader从mysql表读取时间戳。 When I look at the data in the table it is in the format 2013-09-12 11:11:09 . 当我查看表中的数据时,其格式为2013-09-12 11:11:09 But the reader seems to read it in the format 12/09/2013 11:11:09 . 但读者似乎是以12/09/2013 11:11:09的格式12/09/2013 11:11:09

I then try to insert this into another mysql table but receive the error: 然后,我尝试将其插入另一个mysql表,但收到错误:

Incorrect datetime value: '12/09/2013 11:11:09' for column 'timestamp' at row 1 第1行的'时间戳'的日期时间值不正确:'12 / 09/2013 11:11:09'

How can I sort out this difference in formatting? 如何解决格式上的差异? Should I be referencing some Unix timestamp value somehow? 我应该以某种方式引用一些Unix时间戳值吗?

The data shouldn't be in the table in any text format. 数据不应以任何文本格式出现在表格中。 It's just a date and time. 这只是一个日期和时间。

You'll see the format when you convert the data to a string - which you should do as rarely as possible. 将数据转换为字符串时,您会看到格式-应该尽量少用。 In particular, when you're inserting the data into a different table, you shouldn't use a formatted value at all - you should use a DateTime in parameterized SQL. 特别是,当您将数据插入到另一个表中时,根本不要使用格式化的值-您应该在参数化SQL中使用DateTime

Basically, unless you really need a string representation of the data, you should keep it in the "native" representation ( DateTime in this case). 基本上,除非您确实需要数据的字符串表示形式,否则应将其保留为“本地”表示形式(在这种情况下为DateTime )。 Every time you have a conversion to or from text, that's an opportunity for failure. 每当您进行文本转换时,这都是失败的机会。 Dates and times are hard enough with time zones etc, without extraneous conversions getting involved. 日期和时间对于时区等来说足够困难,不会涉及无关的转换。

How are you looking at the data "in the table"? 您如何看待表格中的数据? I'm not familiar with the MySQL implementation, but with Oracle and Sql Server datetime values are stored in an unreadable binary format, and translated to a readable timestamp by the query tool. 我不熟悉MySQL的实现,但是使用Oracle和Sql Server的日期时间值以不可读的二进制格式存储,并通过查询工具转换为可读的时间戳。 MySQL is likely doing something similar. MySQL可能正在做类似的事情。

try to insert this into another mysql table 尝试将其插入另一个mysql表

If you care about format when you're inserting the data, you're doing something really bad . 如果您在插入数据时关心格式,那么您所做的事情确实很糟糕 That's a strong indication you're using a technique that will be vulnerable to sql injection attacks, rather than parameterized queries. 这强烈表明您使用的是易受sql注入攻击而不是参数化查询攻击的技术。 If you use parameterized queries, you assign a C# datetime type to the query parameter value directly, and the ADO.Net object handles any formatting you need. 如果使用参数化查询,则直接将C#日期时间类型分配给查询参数值,而ADO.Net对象将处理所需的任何格式。 At that point, anything you can successfully DateTime.Parse() or DateTime.TryParse() becomes a valid input for your query. 那时,您可以成功将DateTime.Parse()DateTime.TryParse()成功的任何内容变为查询的有效输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM