2

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 :

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

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. and when I choose the date (From 05/02/2016 to 05/02/2016 ) there is no records here. Can someone tell me what I'm doing wrong here?

4
  • your dateTimePicker1 is sending time stamp also to SQL, try to pass only Date Commented Apr 27, 2016 at 13:58
  • This code is vulnerable to sql injection attacks. Commented Apr 27, 2016 at 14:01
  • @JoelCoehoorn Have you any idea how to secure it ? Commented Apr 27, 2016 at 14:16
  • parameterized queries. Query parameters also have the nice features of being faster and avoiding issues with single quotes in fields or formatting issues with dates. Commented Apr 27, 2016 at 16:24

2 Answers 2

8

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));
Sign up to request clarification or add additional context in comments.

Comments

1

Try to pass only Date value instead of DateTime value

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

4 Comments

@Y.Arsoy you should mark the answer as the correct solution if it solved your problem.
@tobypls I am new here , I didn't find where should i mark it solved ?
@Y.Arsoy - there should be a tick mark right below down arrow left to this answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.