Reputation: 13
I have an application that pulls a date from a MySQL database (string format: 01-jan-2000). I need to compare this data with the date entered in a TextBox.
This is what i have so far:
String query = "select * from tb_demographic_data where date_of_birth LIKE '%" +
txb_startDate.Text + "' OR (str_to_date(date_of_birth,'%d,%b,%Y') <=
str_to_date('"+txb_startDate.Text+"','%d,%b,%Y'))
When I run the query I get no results. Nothing is wrong with my sql code. I think the error occurs when i change the string to a date with str_to_date()
. Can anyone help?
Upvotes: 0
Views: 418
Reputation: 13
i figured it out. I'm sure its not the most efficient way to do this but I'm fairly new to this. Here it is: I just parsed the two strings as dates and calculated the date difference between them. If the answer is positive then the first date comes before the second and vice versa
select * from tb_demographic_data
where date_of_birth
LIKE '%" + txb_startDate.Text + "'
OR (datediff(str_to_date('" + txb_startDate.Text + "',
'%d-%b-%Y'),
str_to_date(date_of_birth,
'%d-%b-%Y'))>=0)
Upvotes: 0
Reputation: 8047
As Nikhil pointed out, having a user enter a date in a date/calendar/clock control is typically a much better choice. In addition, I would highly recommend not taking user input from a textbox and simply pasting it inside a SQL string. This leads to SQL injection.
I would recommend that you either use one of the above recommended controls to have users specify a specific DateTime
, or convert the data in your text box to a DateTime
object. Assuming you are using DbCommand
objects to run your query, you can then use a parameterized query and pass in your DateTime
as a parameter, rather than directly putting it into the command. Your SQL could look like the following:
select * from tb_demographic_data
where date_of_birth <= @startDate
You would then have to add a DbParameter
to your DbCommand
with a ParameterName
of "@startDate"
and a Value
of your DateTime
object.
Upvotes: 0
Reputation: 6515
Don't do string comparisons of dates. Change the column in the database to be a date, and update your query to accept a date value using a parametrized statement or similar.
Upvotes: 1
Reputation: 27627
It looks like your date format is wrong... '%d,%b,%Y'
is saying that the separators are commas. I would imagine you want something like '%d-%b-%Y'
.
Upvotes: 0