I have code like this:
AutoParkDataDataContext Db = new AutoParkDataDataContext();
Dailyreport dailyRep = new Dailyreport();
string time = Convert.ToDateTime("10-10-2014 15:00:00");
dailyRep.order_time = time;
Db.Dailyreports.InsertOnSubmit(dailyRep);
Db.SubmitChanges();
When I see it in the DailyReport table it shows me only the date ("10-10-2014 00:00:00:00"), so the time is ignored. How could i fix it?
The column type is DateTime.
A quick/easy method to insert date or datetime into MySQL is to use the format 'yyyy-MM-dd', or datetime as 'yyyy-MM-dd H:mm:ss'.
Try this
DateTime theDate = DateTime.Now;
theDate.ToString("yyyy-MM-dd H:mm:ss");
Make your SQL look like this.
insert into mytable (date_time_field) value ('2013-09-09 03:44:00');
Your line:
string time = Convert.ToDateTime("10-10-2014 15:00:00");
Shouldn't compile.
I can only guess that you don't have DateTime as type of your column in SQL Server, you should modify it to keep DateTime and then pass a DateTime type object, not a string.
This means that the underlying data type in the database must be Date. Change that to DateTime and it will store the time as well.
DateTime dateTimeVariable = DateTime.Now;
string date = dateTimeVariable.ToString("yyyy-MM-dd H:mm:ss");
The insert Statement will look kind of like this:
string InsertQuery = "INSERT INTO table( `fieldName` ) VALUES ( '" + date + "' )";
Related
I want to copy a selected date from a monthCalender control to a sqlite db in c#.
Tried to do it with ToString : Gave me this form of string (MM-DD-YYYY-00:00:00 AM) and a logic error
from sqlite.
Tried doing it with ToShortDateString: It gave me this string (MM-DD-YYYY).
No error from sqlite until checking the record again.This time the error was "string was not recognized
as a valid DateTime".
I know the date format for sqlite is YYYY-MM-DD.
Do I have to convert the string?
string startdate = monthCalendar1.SelectionRange.Start.ToShortDateString();
string query = $"UPDATE status SET user = {listBox1.SelectedValue}" +
$" , userbadge = {listBox2.SelectedValue} "+
$" , date = {startdate}" +
$" WHERE status.id = {index}";
openConnection();
SQLiteCommand com = new SQLiteCommand(query, connection);
com.ExecuteNonQuery();
closeConnection();
I think you can mitigate your problem simply by using Parameters:
command.CommandText =
#"
UPDATE status SET user = $user, userbadge = $userbadge, date = $startdate WHERE status.id = $index
";
command.Parameters.AddWithValue("$user", listBox1.SelectedValue);
command.Parameters.AddWithValue("$userbadge", listBox2.SelectedValue);
command.Parameters.AddWithValue("$startdate ", startdate );
command.Parameters.AddWithValue("$index", index);
According to this docu, the value will be saved as "yyyy-MM-dd HH:mm:ss.FFFFFFF".
The solution with the parameters resulted in the same error.
After searching a bit further I found out that maybe converting the string would
do the job. And yes it worked!!!
DateTime datetime = Convert.ToDateTime(startdate);
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);
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");
In my SQL stored procedure:
#StartDate as smalldatetime,
#EndDate as smalldatetime
In my C# code:
StartDate = new DateTime(1901,01,01,00,00,00);
EndDate = new DateTime(2200,01,01,00,00,00);
var StartDate2 = StartDate.ToString("dd/MM/yyyy HH:mm:ss");
StartDate2 = DateTime.ParseExact(StartDate2, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy HH:mm:ss");
StartDate = Convert.ToDateTime(StartDate2);
var EndDate2 = EndDate.ToString("dd/MM/yyyy HH:mm:ss");
EndDate2 = DateTime.ParseExact(EndDate2, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy HH:mm:ss");
EndDate = Convert.ToDateTime(EndDate2);
The column is as a smalldatetime type in the db. I'm going round in the circles with this! whats the correct way to parse my Dates to the correct format for querying in the db?
UPDATE:
Changed code to this and worked fine.
SqlParameter parameter = daHoliday.SelectCommand.Parameters.Add("#StartDate", System.Data.SqlDbType.SmallDateTime);
SqlParameter parameter2 = daHoliday.SelectCommand.Parameters.Add("#EndDate", System.Data.SqlDbType.SmallDateTime);
parameter.Value = StartDate;
parameter2.Value = EndDate;
Don't convert them to string, just pass them as DateTime type object through Command Parameters.
DateTime should never be converted to string to match format of data in database table. If the datatype in table is DateTime then its always better to pass the .Net framework DateTime object as parameter to command.
I'm trying to insert a value from a datetimepicker value to a SQL Server table.
My table looks like this
Profile (Id, Name,..., DateofBirth(date)...)
I have tried this to convert datetime picker value to
string dt = dateTimePicker.Value.ToString("yyyy-mm-dd hh:MM:ss");
Insert into profile (id, DateofBirth)
values(id, CONVERT(datetime, CONVERT( varchar(11), dt, 101));
also use this
var date = new DateTime(dateTimePickerText);
also use this
DateTime date = DateBox.Value.Date;
string sDate = date.ToString("dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture);
DateTime dateInsert = Convert.ToDateTime(sDate);
but can't able to insert the date into the database. 2nd how can I retrieve back the date from database?
You must have to use SqlParameter.
sql="Insert into profile (id, DateofBirth) values (#id,#DateofBirth)";
using(SqlCommand cmd=new SqlCommand(sql,conn))
{
cmd.Parameters.Add("#id",SqlDbType.Int).Value=10;
cmd.Parameters.Add("#DateofBirth",SqlDbType.DateTime).Value=dateTimePicker.Value;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Personally I'd get into the habit of using parameters for all of your SQL queries. That way you avoid SQL injection attack vector and you can also specify the parameter type as datetime. See this answer for example.