简体   繁体   English

C# 日期时间 MySQL 命令

[英]C# DateTime MySQL Command

I am having issues with using the DateTime as the parameter to work for a sql query.我在使用 DateTime 作为参数来处理 sql 查询时遇到问题。

Here is the query I would like:这是我想要的查询:

command.CommandText = "SELECT idGameNumber FROM GameOutcome WHERE GameOutcome.gameDate = <insert DateTime game_time>";

where game_time is a DateTime object and Gameoutcome.gameDate is a DATETIME datatype.其中 game_time 是 DateTime object,Gameoutcome.gameDate 是 DATETIME 数据类型。

What do I need to put on the right side of the = sign in there WHERE clause?我需要在 WHERE 子句中 = 符号的右侧放置什么?

Solution 1: using DateTime string 解决方案1:使用DateTime字符串

MYSQL takes the DateTime in Following default format: MYSQL采用以下默认格式的DateTime

yyyy-MM-dd HH:mm:ss

so you can convert your datetime object into above format . 因此您可以将datetime对象转换为上述format

Try This: 尝试这个:

command.CommandText ="SELECT idGameNumber FROM GameOutcome WHERE GameOutcome.gameDate ='"+ game_time.ToString("yyyy-MM-dd HH:mm:ss")+"'";

Solution 2: using parameterised queries . 解决方案2:使用parameterised queries

you might have already heared about parameterised queries . 您可能已经听说过parameterised queries
Parameterised queries not only avoid sql injection attacks they also provide clean way of sending/passing arguments to feilds in the table. 参数化查询不仅避免了sql injection attacks而且还提供了向表中的字段发送/传递arguments干净方法。

command.CommandText ="SELECT idGameNumber FROM GameOutcome WHERE GameOutcome.gameDate =@gamedate;"    
command.Parameters.AddWithValue("@gamedate",game_time);  

as datetime format in mysql is in yyyy-MM-dd HH:mm:ss format so to use c# DateTime and pass it in query where as parameter:因为 mysql 中的日期时间格式是yyyy-MM-dd HH:mm:ss格式所以要使用 c# DateTime并将其作为参数传递到查询where

  1. you can use ToString() method of DateTime variable and format the returned value as: game_time.ToString("yyyy-MM-dd HH:mm:ss")您可以使用DateTime变量的ToString()方法并将返回值格式化为: game_time.ToString("yyyy-MM-dd HH:mm:ss")
command.CommandText = $"SELECT idGameNumber FROM GameOutcome WHERE GameOutcome.gameDate = '{game_time.ToString("yyyy-MM-dd HH:mm:ss")}'";

or you can write the interpolation simpler as:或者您可以将插值写得更简单:

command.CommandText = $"SELECT idGameNumber FROM GameOutcome WHERE GameOutcome.gameDate = '{game_time:yyyy-MM-dd HH:mm:ss}'";

the longer version to use:要使用的较长版本:

DateTimeFormatInfo isoFormat = CultureInfo.InvariantCulture.DateTimeFormat;

dateValue.ToString(isoFormat.SortableDateTimePattern); 

dateValue.ToString(isoFormat.UniversalSortableDateTimePattern)

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

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