inserting datetimepicker value to SQL Server 2008 - c#

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.

Related

save time into SQL Database

I have a SQL Database with the following structure:
I have 4 MaskedTextBox for:
(Structure)
DateFrom: 0000.00.00
DateFromTime: 00:00:00
DateTo: 0000.00.00
DateToTime: 00:00:00
.
SqlCommand cmd = new SqlCommand("INSERT INTO TABELLE2 (MessageHeadline, MessageText, SpecifyUser, CreateDate, CreateTime, CreateUser, DateFrom, DateFromTime, DateTo, DateToTime) VALUES (#MessageHeadline, #MessageText, #SpecifyUser, #CreateDate, #CreateTime, #CreateUser, #DateFrom, #DateFromTime, #DateTo, #DateToTime)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MessageHeadline", TB_MSGHeadline.Text);
cmd.Parameters.AddWithValue("#MessageText", TB_MSGText.Text);
cmd.Parameters.AddWithValue("#SpecifyUser", TB_SpecifyUser.Text);
cmd.Parameters.AddWithValue("#CreateDate", CreateDate );
cmd.Parameters.AddWithValue("#CreateTime", CreateTime);
cmd.Parameters.AddWithValue("#CreateUser", CreateUser);
cmd.Parameters.AddWithValue("#DateFrom", MTB_DateFrom.Text);
cmd.Parameters.AddWithValue("#DateFromTime", MTB_DateFromTime.Text);
cmd.Parameters.AddWithValue("#DateTo", MTB_DateTo.Text);
cmd.Parameters.AddWithValue("#DateToTime", MTB_DateToTime.Text);
connection.Open();
cmd.ExecuteNonQuery();
TB_MSGHeadline.Clear();
TB_MSGText.Clear();
TB_SpecifyUser.Clear();
And finally I want to save these values from my MasketTextBox into my database to use them later.
I try to change the Structure and try some SQL Date/Time formation but i get the error:
You're passing the DATE parameters in the incorrect format. You need to pass them as a valid DateTime which your MaskedTextBox values do not appear to be.
For example, #DateFrom is a SQL Date data type. You should pass it a valid parameter such as a DateTime:
cmd.Parameters.AddWithValue("#DateFrom", DateTime.Now);
You may need to parse the MaskedTextBox values correct using DateTime.TryParse
DateTime parsedDate;
bool success = DateTime.TryParse(MaskedInputOne.Text, out parsedDate);
if (success) {
cmd.Parameters.AddWithValue("#DateFrom", parsedDate);
}
In this case we are only adding the parameter if the conversion succeeds.

datetime in C# vs, SQL and GETDATE() from SQL Server

I use GETDATE() in a SQL Server stored procedure to insert a date into the SQL Server database table.
After that I need to implement a C# function which is based on datetime input parameter finds if the date was saved in the tables.
The datetime in C# and SQL are different. How do I convert from C# datetime to SQL datetime which has a form of yyyy-mm-ddT:yy:mm:ss.mmm? I need to specify explicitly yyyy-mm-ddT:yy:mm:ss.mmm.
Will be happy for all propositions/possible ways.
DateTime in .Net framework and SQL Server (if it is DateTime type field) is irrespective of the format. Format is only useful for displaying output.
If your field in SQL Server is of DateTime type then you can query it from C# code using parameterized query something like:
public DataTable GetRecords(DateTime dtParameter)
{
DataTable dt = null;
using (SqlConnection conn = new SqlConnection("connection string"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * from yourTable where DateField = #dateparameter"))
{
conn.Open();
cmd.Parameters.AddWithValue("#dateparameter",dtParameter);
SqlDataReader dr = cmd.ExecuteReader();
//...rest of the code
dt.Load(dr);
}
}
return dt;
}
Datetimes between C# and SQL are 100% compatible. The format shouldn't make any difference if you are passing them as DateTimes. If you are generating a SQL string then I would highly recommend changing to SQL Parameters so you don;t have to worry about any formatting issues.
A datetime has no format at all, it has a value. SQL-DateTimes and C# DateTimes are compatible. So don't convert it (to string) at all but pass it as datetime-parameter to the database.
Then you're safe if the DateTime value is within SqlDateTime.MinValue(January 1, 1753) and SqlDateTime.MaxValue(December 31, 9999).
You should never write DateTime.Now from client code to insert into the database as this will be based on the clients local time; do this
public DateTime GetDatabaseTime()
{
var parameter = new SqlParameter("time", SqlDbType.DateTime2)
{
Direction = ParameterDirection.Output
};
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var command = new SqlConnection("SELECT #time = SYSDATETIME()", connection))
{
command.ExecuteNonQuery();
}
}
return (DateTime)parameter.Value;
}
Also you should never use DATETIME in SQL Server you should always use DATETIME2 as DATETIME is less accurate than C#::DateTime and it will lead to rounding errors. I know this from bitter experience.
If you are using Entity Framework, and your database is using datetime and not datetime2, the trick is to use SqlDateTime to match the fact that .Net goes to nanosecond, versus sql's millisecond precision. You can use your DateTime variable in .net.. for a SqlDateTime instance, and then you can uniquely identify a record down to the millisecond.
System.Data.SqlTypes.SqlDateTime entry2 = new System.Data.SqlTypes.SqlDateTime(new DateTime(dto.LookUpDateTime));
DateTime entry = entry2.Value;
var existticket = from db in context.Tickets
where db.LookupDateTime == entry && db.UserId == UserId
select db;

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");

format string in datetime c# to insert in MYSQL datetime column

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 + "' )";

Error when updating date field in sql server using c#

I am trying to insert a date (date only, not datetime) into sql table (the datatype is date).
I am using the '23/07/2013' format which I am getting from jquery datepicker.
When I execute the following sql, I am getting following error.
SQL: UPDATE qmsAuditFindings SET FindDate='23/07/2013' WHERE AuditID=37
Please advise.
Also its worth mentioning that the insert statement with the exact format works just fine. Just the update that does not.
At the surface, this is simply a formatting issue - but "fixing the formatting" is the wrong way to address this; you should parameterize, such that formatting simply does not apply. Dates don't have a "format", as such - they are just numbers. For example, what we should probably execute is:
UPDATE qmsAuditFindings SET FindDate=#findDate WHERE AuditID=#auditId
To do that you get the DateTime value in your .NET code, and do something like:
DateTime findDate = ...
int auditId = ...
using(var cmd = connection.CreateCommand()) {
cmd.CommandText =
"UPDATE qmsAuditFindings SET FindDate=#findDate WHERE AuditID=#auditId";
cmd.Parameters.AddWithValue("findDate", findDate);
cmd.Parameters.AddWithValue("auditId", auditId);
cmd.ExecuteNonQuery();
}
or more simply with a tool like "dapper":
DateTime findDate = ...
int auditId = ...
connection.Execute(
"UPDATE qmsAuditFindings SET FindDate=#findDate WHERE AuditID=#auditId",
new { findDate, auditId });

Categories