Date Time Picker Comparison not displaying values - c#

In my MySQL database, I am using a DATETIME type to log events. The format is yyyy-MM-dd HH:mm:ss
I am trying to use a Windows Form to display events from a particular range. However, I am not receiving any values with my query. I tried a simple select * and that worked, but not when I tried to use parameters. This is what I have thus far. I know I am very close, just missing something small, I suspect:
String query = "SELECT Device FROM log WHERE Stamp >= #p_StartDate AND STAMP <= #p_EndDate;
OdbcCommand command = new OdbcCommand(query, myConnection);
command.Parameters.AddWithValue("#p_StartDate", fromDate.Value); // name of dateTimePicker
command.Parameters.AddWithValue("#p_EndDate", endDate.Value); // name of dateTimePicker2
OdbcDataAdapter adp = new OdbcDataAdapter(command);
DataSet set = new DataSet();
adapter.Fill(set);
dataGridView1.DataSource = set.Tables[0];
My Date Time Pickers have a Custom Format of yyyy-MM-dd HH:mm:ss as well so the DateTime should match up but they don't seem to, for some reason.

Related

Adding time to SQL date query

var datadb1 = DateTime.ParseExact(dateTimePicker1.Text, "dd/MM/yyyy", null);
var timedb1 = DateTime.ParseExact(dateTimePicker2.Text, "HH:mm:ss", null);
var datadb2 = DateTime.ParseExact(dateTimePicker3.Text, "dd/MM/yyyy", null);
var timedb2 = DateTime.ParseExact(dateTimePicker4.Text, "HH:mm:ss", null);
commanddb.CommandText =
"SELECT * FROM testtab WHERE datatime >= #from and datatime < #to";
commanddb.Parameters.AddWithValue("#from", datadb1);
commanddb.Parameters.AddWithValue("#to", datadb2);
Need to add time check to this query (I`m getting time info from dateTimePicker2 and dateTimePicker4).
Need to add time check to this query
The problem with your code is that you are passing only the date part to check to the SQL query. In order to make your query check both the date and time parts, you have to:
Declare the SQL parameters of data type datetime(SqlDbType.DateTime).
The value you are passing to the sql parameter should be of data type DateTime and contains both parts the date and time parts.
One way to achieve this is by using the same DateTimePciker to pass both date and time parts, then don't use the datetimepicker Text property and use DateTimePicker.Value property instead, it will give you both date and time parts:
SqlParameter fromParam= new SqlParameter("#from", SqlDbType.DateTime);
fromParam.Value = dateTimePicker1.Value;
SqlParameter toParam= new SqlParameter("#to", SqlDbType.DateTime);
toParam.Value = dateTimePicker2.Value;
commanddb.Parameters.Add(fromParam);
commanddb.Parameters.Add(toParam);
Or, by adding both the date part and time part coming from different datetimepickers to the same DateTime variable before passing it to the sql parameter. Something like this:
var datadb1 = DateTime.Parse(dateTimePicker1.Value.ToShortDateString());
var timedb1 = DateTime.Parse(dateTimePicker2.Value.ToShortTimeString());
DateTime datetimeCombined1 = datadb1 + new TimeSpan(timedb1.Hour,
timedb1.Minute,
timedb1.Second);
Then you have to pass this variable datetimeCombined1 to the SQL parameter, the same with the second datetime range, you have to combine both the parts before passing it.
This is assuming that you are using dateTimePicker1 to read the date part only and the dateTimePicker2 to read the time part only.
If you want to use each dateTimePicker for Date or Time seperatly you can define a DateTime variables and Set its Date value and Time Value like this:
DateTimePicker dateTimePickerFromDate = new DateTimePicker();
DateTimePicker dateTimePickerFromTime = new DateTimePicker();
DateTimePicker dateTimePickerToDate = new DateTimePicker();
DateTimePicker dateTimePickerToTime = new DateTimePicker();
DateTime fromDateTime = new DateTime(dateTimePickerFromDate.Value.Year,
dateTimePickerFromDate.Value.Month, dateTimePickerFromDate.Value.Day,
dateTimePickerFromTime.Value.Hour, dateTimePickerFromTime.Value.Minute,
dateTimePickerFromTime.Value.Second);
DateTime toDateTime = new DateTime(dateTimePickerToDate.Value.Year,
dateTimePickerToDate.Value.Month, dateTimePickerToDate.Value.Day,
dateTimePickerToTime.Value.Hour, dateTimePickerToTime.Value.Minute,
dateTimePickerToTime.Value.Second);
commanddb.CommandText =
"SELECT * FROM testtab WHERE datatime >= #from and datatime < #to";
commanddb.Parameters.AddWithValue("#from", fromDateTime);
commanddb.Parameters.AddWithValue("#to", toDateTime);

How to get short date format from the datetime object

I am capturing the time in the text box (by using AJAX calender extender)
the time in the string is 12/10/2013, but when I assign the string to a datetime object it is converted into 12/10/2013 12:00:00 AM.
I want to use the date to filter the records in the database using the query below. Please help
string date1 = txtDate1.Text;
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName,Story.StoryId,COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=" + date1 + "
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC ;";
It's generally not a good idea to pass dates as strings in your queries because you will most likely run into formatting issues - leave it up to the Framework you are using decide on what the best format is.
In your circumstances, you can do this by using SqlParameters e.g.
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName, Story.StoryId, COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=#dateTime
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC";
using (SqlConnection connection = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand(strQuery, connection))
{
cmd.Parameters.AddWithValue("#dateTime", date);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
}
}
Another important reason to use parameters when writing raw SQL is to ensure your user input is correctly sanatized and safe to pass to the DB. Failure to do this can leave you open to various exploitations such as SQL Injection.
Instead of DateTime object you can use Date object.
DateTime is an integer interpreted to represent both parts of DateTime (ie: date and time). You will always have both date and time in DateTime.
ex:
DateTime.Now.ToString("MM/dd/yyyy");

Insert date into SQL without taking care of the regional settings

my question looks simple: in my client/server application I want to record a specific date provided by the client.
The problem is that I don't know the regional settings of the client, and I don't know the regional settings of the SQL Server.
How can the client application provide a date in whatever format (last login of a specific user) and store it in a SQL Server table that might be installed with a different regional settings (french, english, italian, german, etc...).
Simple: don't use strings. Use a parameter that is typed as a datetime; can be as simple as:
DateTime when = ...
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "... #when ...";
cmd.Parameters.AddWithValue("when", when);
cmd.ExecuteNotQuery();
}
or with "dapper":
conn.Execute("... #when ...", new { when });
Dates/times are actually just numbers. It is only when you write/parse it as a string that formatting is an issue.
Just store everything in UTC date in sqlserver. And while retrieving the date convert the utc date to the timezone of the user. I hope users timezone is maintained in your database.
You will need a timezone table and a conversion function that will convert the UTC time to the users local time.
to insert a date in SQL use a string in the form 'YYYYMMDD'
what comes from the client-side you sould know what is it
You should use Parameters, but you also can format date to ISO format by date.ToString("s")
Use datetime format, and store dates as UTC time.
You'll probably also be interested in datetimeoffset.
Validation part
DateTime dt;
string YourDate = "Your Date";
if (DateTime.TryParse(YourDate, out dt))
{
//Your Code
}
Stored Procedure Record Insertion/Retrieval
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand();
string expression = "Date Parameter value";
DateTime dt;
if (DateTime.TryParse(expression, out dt))
{
//Your Code
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (IDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
}
}
}
While storing the data in Sql Server Keep the data format consistent and synchronized with the data format while retrieving....

Updating datetime in access table

I'm trying to insert a datetime value into a datatable and then use the oledbdataadapter's update(datatable) method to load it into my database.. but i keep getting a "Data type mismatch in criteria expression." error. My access Data types in the table are:
ID Number
Nombre_Proyecto Text
Codigo_Ine_Proy Text
Cliente text
Fecha_Creacion Datetime (short date)
according to access short date is mm/dd/yyy, wich fits with my datetime/toshortdatestring method? i think so at least.
Any help would be appreciated. Here's my code:
Insert OledbCommand fot the data adapter:
sql = "PARAMETERS [#Fecha_Creacion] datetime;INSERT Into [Proyectos] ([ID], [Nombre_Proyecto],[Codigo_Ine_Proy],[Cliente],[Fecha_Creacion]) Values (#ID,#Nombre_Proyecto,#Codigo_Ine_Proy,#Cliente,#Fecha_Creacion)";
Comando = new OleDbCommand(sql, conn);
Comando.Parameters.Add("#Nombre_Proyecto", OleDbType.VarWChar, 500, "Nombre_Proyecto");
Comando.Parameters.Add("#Codigo_Ine_Proy", OleDbType.VarWChar, 500, "Codigo_Ine_Proy");
Comando.Parameters.Add("#Cliente", OleDbType.VarWChar, 500, "Cliente");
Comando.Parameters.Add("#Fecha_Creacion", DbType.DateTime);
Comando.Parameters.Add("#ID", OleDbType.Integer, 10000, "ID");
Part where i create the datarow on my datatable:
DataRow newRow = Tabla_Proyectos_BD_General.NewRow();
Max_IDs["Proyectos"] += 1;
newRow["ID"] = Max_IDs["Proyectos"];
newRow["Nombre_Proyecto"] = textBox2.Text;
newRow["Codigo_Ine_Proy"] = textBox1.Text;
newRow["Cliente"] = textBox3.Text;
string x = System.DateTime.Now.ToShortDateString();
newRow["Fecha_Creacion"] = x;
Tabla_Proyectos_BD_General.Rows.Add(newRow);
You should just use
newRow["Fecha_Creacion"] = System.DateTime.Now;
What you see from in the Access is the "formatted date". When interacting thru OleDB you need to use the DateTime and not the formatted string.
string x = System.DateTime.Now.ToShortDateString();
It's a string, not a datetime! hence mismatch.
newRow["Fecha_Creacion"] = System.DateTime.Now;
And your parameterised query should just do it for you.
if you want to show the date you put in there in shortdatestring format (whate ever that is on the pc that does the formatting, get it as a datetime and then format as required.
PS if you want to pass a date as a string to a database, use the formats yyyy-MM-dd or yyyyMMdd. Any other than the universal and unambiguous date formats is just a bug waiting to happen, and never do unless you have to.
Tip when outputting dates, converting them into strings in some format is the last operation, when inputing them, converting to a datetime from the string is the first thing you should do.
Edited after comment
Simplest solution is
Comando.Parameters.Add("#Fecha_Creacion", DbType.DateTime, System.DateTime.Now);

Date conversion from C# to MySql Format

How to convert C# datetime to MySql Datetime format. I am getting value from text box like 7/27/2011 this format. But i want to convert in this format 2011-7-27. So here i am stuking. Please help me. My objective is to filter the record between two dates and show in a listview control in asp.net.
Here is my code:
DateTime dt1 = Convert.ToDateTime(txtToDate.Text);
DateTime dt2 = Convert.ToDateTime(txtFromDate.Text);
lvAlert.DataSource = facade.GetAlertsByDate(dt1, dt2);
lvAlert.DataBind();
I haven't used MySQL with .NET, but Oracle has similar date conversion issues with .NET. The only way to stay snae with this has been to use parameters for date values, both for input as welll as for WHERE clause comparisons. A parameter created with a MySQL date parameter type, and just giving it a .NET datetime value, should work without needing you to do conversions.
EDITED TO ADD SAMPLE CODE
This code sample shows the basic technique of using parameters for DateTime values, instead of coding conversions to text values and embedding those text values directly in the SQL command text.
public DataTable GetAlertsByDate(DateTime start, DateTime end)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Alerts WHERE EventTime BETWEEN #start AND #end", conn);
DataTable table = new DataTable();
try
{
SqlParameter param;
param = new SqlParameter("#start", SqlDbType.DateTime);
param.Value = start;
cmd.Parameters.Add(param);
param = new SqlParameter("#end", SqlDbType.DateTime);
param.Value = end;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(table);
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
return table;
}
This is SQL Server code, but the technique should be the same for most databases. For Oracle, for example, the only changes would be to use Oracle data access objects, and use ":" in place of "#" in parameter names. The technique for MySQL should also be very similar.
For many databases, shortcuts may exist for creating parameters, such as:
cmd.Parameters.AddWithValue("#start", start);
This works when you know the value is not null, and the correct parameter type can be derived from the C# type of the value. "AddWithValue" is specific to SQL Server; "Add" works also but is obsolete in SQL Server.
Hope this helps.
You can assign format to data time, DateTime.ParseExact() or DateTime.ToString(format), :
the format for 2011-7-27 is yyyy-m-dd
Assuming you are doing this in the database I think you should use date_format to get in the required format
Something like date_format(dateval,'%Y-%c-%d') (Not tested)
I use:
string fieldate = dt1.ToString("yyyy-MM-dd");

Categories