简体   繁体   English

在WindowsForms应用程序c#中的两个日期之间选择查询

[英]select query BETWEEN two dates in WindowsForms Application c#

I have a problem with the query BETWEEN .I'm trying to select records from a table between two dates, SO, I used the following query : 我在查询BETWEEN时遇到问题。我试图从两个日期之间的表中选择记录,因此,我使用了以下查询:

SqlDataAdapter sda1 = new SqlDataAdapter(
  "select distinct * from BLC where DATE_BLC between '" + 
   dateTimePicker1.Value.ToString() + "' and'" + 
   dateTimePicker2.Value.ToString() + "'", conx);

When I enter the following dates : 当我输入以下日期时:

From date 05/02/2016 To date 15/03/2016 从日期05/02/2016至日期15/03/2016

It returns the records between (06/02/2016 to 15/03/2016) date but the records that begin with date 05/02/2016 , they are not returned. 它返回介于(06/02/2016到15/03/2016)日期之间的记录,但不会返回日期为05/02/2016的记录。 and when I choose the date (From 05/02/2016 to 05/02/2016 ) there is no records here. 当我选择日期(从05/02/2016到05/02/2016)时,这里没有记录。 Can someone tell me what I'm doing wrong here? 有人可以告诉我我在做什么错吗?

It is a better codding practice to use parameters as they will sterilize any inputs for any queries and are generally safer to user. 使用参数是一种更好的编码做法,因为参数将对任何查询的任何输入进行消毒,并且通常对用户更安全。 Thus the code would become 因此,代码将成为

SqlDataAdapter sda1 = new SqlDataAdapter("select distinct * from BLC where DATE_BLC between @Date1 and @Date2", conx);
sda1.SelectCommand.Parameters.Add(new SqlParameter("@Date1", dateTimePicker1.Value));
sda1.SelectCommand.Parameters.Add(new SqlParameter("@Date2", dateTimePicker2.Value));

试图通过仅Date ,而不是价值DateTime价值

SqlDataAdapter sda1 = new SqlDataAdapter("select distinct * from BLC where DATE_BLC between '" + dateTimePicker1.Value.Date.ToShortDateString() + "' and'" + dateTimePicker2.Value.Date.ToShortDateString() + "'", conx); 

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

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