简体   繁体   中英

DateTime conversoin for DB querying

I need to convert DateTime to string for purposes of DB querying.

I thought to do something like

_endTime.ToString(_isoDateTimeFormat.UniversalSortableDateTimePattern)

It works with MySQL, but SQL Server causes problems.

The final string looks like 2012-03-01 15:59:00Z seems z not supposed to be there.

Any suggestions?

You shouldn't be performing a text conversion at all.

You should be storing the data as a DATETIME (or whatever the corresponding type is in the database) and then you should be specifying the value in the query using a parameter, not including it in the SQL.

That way you don't need any string conversions in the first place.

Always pass values via parameters unless you have some really, really good reason why you absolutely have to include it in the SQL directly. Using parameters:

  • Protects you from SQL injection attacks
  • Removes conversion annoyances like this one
  • Keeps your code and data more logically separated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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