在 C# 中使用 DateTimePicker 控件时,将 DateTimePicker 的值转换为字符串,并将其包含在 SQL 语句中以执行查询,需要特别注意语法。

错误示例:

public int Select(string production, int condition, DateTimePicker StartTime, DateTimePicker EndTime)
{
    string sql = $@'select count(*)
              from {ProductProductionRecorderTableMainName}{production}
              where {ProductionData}>={StartTime}and {ProductionData}<={EndTime}and{ProductionCondition}={condition} ';
    int result = SqlConnector.ExecuteNonQuery(sql, CommandType.Text);
    return result;
    ;
}

存在语法错误。应该将 DateTimePicker 的值转换为字符串,并在 SQL 语句中使用单引号将其括起来,如下所示:

string sql = $@'select count(*)
              from {ProductProductionRecorderTableMainName}{production}
              where {ProductionData} >= '{StartTime.Value.ToString('yyyy-MM-dd HH:mm:ss')}' and {ProductionData} <= '{EndTime.Value.ToString('yyyy-MM-dd HH:mm:ss')}' and {ProductionCondition} = {condition} ';

解释:

  • StartTime 和 EndTime 都是 DateTimePicker 控件,需要使用 .Value.ToString() 方法将其转换为字符串类型。
  • 在 SQL 语句中,日期和时间值需要用单引号(')括起来,以确保正确解析。
  • yyyy-MM-dd HH:mm:ss 是一个日期时间格式字符串,用于指定转换后的日期时间字符串的格式。

总结:

在使用 DateTimePicker 控件进行 SQL 查询时,务必将 DateTimePicker 的值转换为字符串,并在 SQL 语句中使用单引号将其括起来。这将确保 SQL 语句正确解析,并避免语法错误。

C# DateTimePicker 转换 SQL 语句的语法错误

原文地址: https://www.cveoy.top/t/topic/mwfS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录