【问题标题】:Sql query between two dates with textboxes带有文本框的两个日期之间的 Sql 查询
【发布时间】:2016-09-13 11:44:31
【问题描述】:

我有一个从我的数据库中获取数据的查询,它需要过滤掉用户将填写两个文本框的特定日期之间的数据。 我需要填写文本框,例如:2016-9-13,否则它将不起作用(数据库中的日期也是 2016-9-13)。 但是当它填满网格视图时,单元格会显示:13-9-2016。

我想按如下顺序填写日期:13-9-2016。我该怎么做?我需要改变什么?

这里有一些代码,可以为我提供数据库中的数据。

 connect = new SqlConnection(@"Data Source=LP12;Initial Catalog=Data;Integrated Security=True");
        connect.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = connect;
        cmd.CommandText = "SELECT DrukSensor, FlowSensor, TempSensor, KwaliteitSensor, OlieVerbruik, Toerental, DateTime, Schip FROM SysteemSensorInfo WHERE DateTime BETWEEN @StartDate AND @EndDate";

        cmd.Parameters.AddWithValue("@StartDate", TextBoxBeginDatum.Text);
        cmd.Parameters.AddWithValue("@EndDate", TextBoxEindDatum.Text);
        DataSet ds = new DataSet();
        new SqlDataAdapter(cmd).Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();

【问题讨论】:

  • 如果要查询日期,切勿使用 AddWithValue 传递字符串
  • 还可以考虑使用 DateTimePicker 从您的用户那里获取日期输入,这样他们就不能声称他们的意思是“01/02/2016”是一月两日而不是二月一日。

标签: c# sql database gridview textbox


【解决方案1】:

基本上,解析日期并传递DateTime 值:

cmd.Parameters.AddWithValue("@StartDate", ParseDate(TextBoxBeginDatum.Text));
cmd.Parameters.AddWithValue("@EndDate", ParseDate(TextBoxEindDatum.Text));

...

static DateTime ParseDate(string text) {
    // TODO; possibly just: return DateTime.Parse(text);
}

【讨论】:

    【解决方案2】:

    你应该使用 Datediff() 函数。在内部,它将以任何格式管理有效日期以进行日期比较。

    "SELECT DrukSensor, FlowSensor, TempSensor, KwaliteitSensor, OlieVerbruik,     Toerental, DateTime, Schip 
    FROM SysteemSensorInfo 
    WHERE datediff(day,DateTime,@StartDate)<=0 AND datediff(day,DateTime,@EndDate)>=0"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 2015-04-01
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多