【问题标题】:C# DateTime MySQL CommandC# 日期时间 MySQL 命令
【发布时间】:2013-12-11 22:57:58
【问题描述】:

我在使用 DateTime 作为参数来处理 sql 查询时遇到问题。

这是我想要的查询:

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

其中 game_time 是 DateTime 对象,Gameoutcome.gameDate 是 DATETIME 数据类型。

我需要在 WHERE 子句中的 = 号右侧放什么?

【问题讨论】:

    标签: c# mysql


    【解决方案1】:

    解决方案一:使用DateTime字符串

    MYSQL 采用以下默认格式的DateTime

    yyyy-MM-dd HH:mm:ss

    这样您就可以将您的datetime 对象转换为上面的format

    试试这个:

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

    解决方案 2: 使用 parameterised queries

    您可能已经听说过parameterised queries
    参数化查询不仅避免了sql injection attacks,它们还提供了向表中的字段发送/传递arguments 的简洁方式。

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

    【讨论】:

      【解决方案2】:

      因为 mysql 中的日期时间格式是 yyyy-MM-dd HH:mm:ss 格式,所以要使用 c# DateTime 并将其作为参数传递给查询 where

      1. 您可以使用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")}'";
      

      或者您可以将插值更简单地编写为:

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

      要使用的较长版本:

      DateTimeFormatInfo isoFormat = CultureInfo.InvariantCulture.DateTimeFormat;
      
      dateValue.ToString(isoFormat.SortableDateTimePattern); 
      
      dateValue.ToString(isoFormat.UniversalSortableDateTimePattern)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-23
        • 2012-05-13
        • 1970-01-01
        • 2011-03-01
        • 2013-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多