I Need To Validate Entair date in Start and end date - c#

string queryStr = "SELECT * from Task_Report_Table where convert(varchar, date, 105) between '" + txtStartDate.Text.ToString() + "' and '" + txtEndDate.Text.ToString() + "' ";
This is the Query I am Using for Retriving the Value from database.
In database table Task_Report_Table have the coloums date,Name,Task and Hours.Here Date is Datetime datatype ,So In Query Convert into String and Iam matching th
I have an UI With Start date and End Date .By giving the date in UI .The above Mention Query Will have to display the Records.
If Iam Giving Start date 07-07-2012 and end date as 12-07-2012.It displays the Values in between 07-07-2012 and 12-07-2012 values.But The Thing is that It displaying Next month and previous months Records and Next year and previous year records also If the records present in database.
The Prob's is It validating day only.but not Month and Year.
I need to validate for day,month,year Which iam Giving in the UI.

You do NOT want to ever write the SQL like that, don't concat strings together, it's so easy to hack (with SQL injection) a site with this kind of code.
Try this:
SELECT * from Task_Report_Table where date between #startdate and #enddate
and then add startdate and enddate as SqlParameter to the SqlCommand you're using, like so:
SqlCommand command = new SqlCommand(yourSQL, connection);
command.Parameters.Add(new SqlParameter("startdate", DateTime.Parse(txtStartDate.Text)));
command.Parameters.Add(new SqlParameter("enddate", DateTime.Parse(txtEndDate.Text)));

The Prob's is It validating day only.but not Month and Year. I need to
validate for day,month,year
This convert(varchar, date, 105) will give you a string that looks like this 27-07-2012 not a date. So your query compares strings not dates.
Use date parameters as suggested by #SteenT.

try like this
put two variables for textboxes..
txtStatrdate.text=strdate;
txtEndDate.text=enddate ;
CONVERT(VARCHAR(10),date,101) BETWEEN CONVERT(DATETIME,strdate,101) AND
CONVERT(DATETIME,enddate,101)

Related

Date Time Format problem between MariaDB and C#

I am trying to retrieve some data from MariaDB database to a datagridview in a C# form application. If I am adding a date condition in the query string, it seems like not returning anything. Is it the problem with the date format? Or is it the problem with my query string? Thank you
// selected date is chosen through date time picker
// format is 24/01/2020 10:10:10
selectedDate = dateTimePicker1.Value;
string query = "SELECT Voltage, Current FROM data_table WHERE device_id='" + Device_ID + "' AND data_date >'"+ selectedDate +"'";
//MariaDB date format is 2020-01-24 09:09:09

Filter Date Range in Datagridview didn't work if months are different

I know this is an old problem but I still confuse a little bit, please show me how.
I loaded a datatable with conditions in datagridview like the code below, thing is, It worked well when FromDate and ToDate are the SAME MONTH. Different month makes the datagridview empty.
FromDate and ToDate are selected in calendar into the 2 textbox.
private void LoadWorkRequestSearch()
{
DateTime datefrom = Convert.ToDateTime(textdatefrom.Text.Trim());
DateTime dateto = Convert.ToDateTime(textdateto.Text.Trim());
string sql = "";
sql = "Select DateCreated, ri.RequestID, RequesterID, RequestStatus, RequestDetail, SentTo, EstimateCompleteDate, ru.StartedDate, ru.ProcessTime From [RequestInfo] ri ";
sql = sql + " LEFT JOIN [StatusRequest] sr ON sr.RequestStatusID = ri.Status";
sql = sql + " LEFT JOIN [RequestUsers] ru ON ru.RequestID = ri.RequestID ";
sql = sql + " Where DateCreated between '" + datefrom.ToShortDateString() + "' and '" + dateto.ToShortDateString() + "'";
_dtworkrequestsearch = _cls_DB.QueryDataTable(sql);
G1.DataSource = _dtworkrequestsearch;
}
I tried everything I searched but it didn't work the way I want, please help.
Thank you,
Use a Calendar Control and enforce a date format.
The conversion to date from TextBox is the likely problem, eg dd/MM into MM/dd
Edit:
You're using a varchar(10) field for dates. That doesn't allow SQL BETWEENS because it's a text field not numeric/date based, so it performs an alphanumeric search.
Use a SmallDateTime column for DateCreated to get the desired results.

Checking if a given date is before current date in c# and mySql

This is my code:
string query = "UPDATE tblschedule Set Status='" + "Complete" + "'Where Date <= '"+ DateTime.Now +"';";
It is working if the date in the sql table is one month ahead. For example:
Given Date: 4/9/2017
Date Now: 3/9/2017
And the status will not change because it was not before the current date.
But when it is not one month ahead. For example:
Given Date: 3/20/2017
Date Now: 3/9/2017
The status will change it to complete even though it is not before the current date.
string query = "UPDATE tblschedule Set Status='Complete' Where STR_TO_DATE(Date,'%m/%d/%Y') <= STR_TO_DATE('"+DateTime.Now+"','%m/%d/%Y')";
Try above code.Hope this will helps.
string query = "UPDATE tblschedule Set Status='" + "Complete" + "'Where
CAST(Date AS DATETIME) <="'+DateTime.Now+"';";
Note that,"Date" parameter in CAST function is the columnname

Return date value into DateTime

After i create an insert statement i want to know two values, the last inserted id and the date.
This is my insert statement
cmd.CommandText = "INSERT INTO message (user_id, category_id, media) " +
"VALUES (:user_id, :category_id, :media)" +
"RETURNING id, TO_DATE(TO_CHAR(creation_date, 'YYYY-MM-DD HH24:MI:SS'), 'YYYY-MM-DD HH24:MI:SS') INTO :last_insert_id, :last_creation_date";
The parameter
cmd.Parameters.Add(new OracleParameter()
{
ParameterName = ":last_creation_date",
OracleDbType = OracleDbType.Date,
Direction = ParameterDirection.Output
});
When i try to get the date, only the year, month and day returns with 00:00:00...
DateTime.Parse(cmd.Parameters[":last_creation_date"].Value.ToString())
How can i receive the full datetime from the value?
A couple of things:
Take a look at the docs for OracleDbType. You are using OracleDbType.Date, which maps to an Oracle DATE type - which is just a date. You should probably use OracleDbType.TimeStamp, or whatever type matches the column you're working with.
Mitch is correct in the question comments. You have entirely too much conversion to and from strings. In the vast majority of cases, you should not use a string to represent a date or time in a database, or in the client code that communicates with a database. Your SQL should change simply to:
RETURNING id, creation_date INTO :last_insert_id, :last_creation_date
Likewise, your .NET code should be similar to:
DateTime dt = (DateTime) cmd.Parameters[":last_creation_date"].Value;

How to access data from sql server 2008 table of a specific date in c#?

In my window application I want to show records held between two dates. I used datepicker to select dates. In sql server 2008 table I used data type [date] to store date. My problem is that it is not working properly to catch the first date, it catches next date to which I select. I used following code :
cmd5.Parameters.AddWithValue("date1", dateTimePicker4.Value);
cmd5.Parameters.AddWithValue("date2", dateTimePicker5.Value);
and when I try this :
cmd5.Parameters.AddWithValue("date1", dateTimePicker4.Value.AddDays(-1));
cmd5.Parameters.AddWithValue("date2", dateTimePicker5.Value);
Result-
my complete code
cmd10 = new SqlCommand("select a_id,commtyp,convert(varchar(10),date,105),comm,primm,c_id,agent from comm where a_id= '" + textBox1.Text + "' AND date >= #date1 AND date <= #date2 ", agr);
cmd10.Parameters.AddWithValue("#date1", dateTimePicker1.Value.AddDays(-1));
cmd10.Parameters.AddWithValue("#date2", dateTimePicker2.Value);
adp = new SqlDataAdapter(cmd10);
DataSet ds = new DataSet();
adp.Fill(ds, "comm");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "comm";
checkBox2.Checked = false;
groupBox15.Show();
cmd10.Parameters.Clear();
You are using value property from datepicker and it's giving you date with seconds and milliseconds. You have to get the actual datepart from it's value.
try this
dateTimePicker4.Value.Date
instead of
dateTimePicker4.Value
you are taking datetime picker and in query may be you are taking from and to dates as datetime.
pleases convert #from and #to datetime in to date as
cast(#From as date)
cast(#To as date)
and then put into condition, it may resolve your problem..

Categories

Resources