Insert date in to database from dd/MM/yyyy formatted string - c#

In windows form I have DateTimePicker with custom format dd/MM/yyyy.
I want to insert the selected date to SQL Local DB but it throwing an exception.
Conversion failed when converting date and/or time from character string
my question is:
How to insert this date into a database in any format.
Here is my code
string query = "Insert into myTable Values('" + dateTimePicker1.Text + "');";

Use DateTimePicker.Value instead of DateTimePicker.Text. If you only want the date part, you could use DateTimePicker.Value.Date.
DateTimePicker.Value is the actual DateTime object assigned to the control, whereas DateTimePicker.Text is the Value property with formatting applied. Using Value directly saves you from having to convert the Text to a DateTime first.
You should also use a parameterized query, as others have noted.
string query = "Insert into myTable Values (#myDate)";
using(SqlConnection connection = new SqlConnection(connectionString))
{
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("myDate", dateTimePicker1.Value);
}
}

Related

Changing the format of a DateTime field when inserting into SQL Server database using SqlCommand

I have the following SqlCommand that inserts a row of data to a SQL Server database table. In particular, the Value column is of datatype DateTime.
When the command is ran, the date format is:
Sep 11 2003 12:00AM
Data when viewing in SQL Server database
However, it needs to be 2003-10-11
When I view it in an application, the date column is blank, but when I change the data directly in the database to match yyyy-mm-dd, the column value is visible in the application.
How do I change the format of the date?
using (SqlConnection connection = new SqlConnection(newConnStr))
{
connection.Open();
string dateOfInterviewQS =
"INSERT INTO PropertyValues(PropertyId, UserId, Value, FriendlyName, LastUpdated, CheckDate) " +
" VALUES(#PropertyId, " + "#UserId, " + "#Value, " +
"#FriendlyName, " + "#LastUpdated, " + "#CheckDate)";
using (var cmd = new SqlCommand(dateOfInterviewQS, connection))
{
SqlParameter date = cmd.Parameters.Add("#Value", SqlDbType.DateTime);
date.Value = DateOfInterview;
cmd.Parameters.AddWithValue("#PropertyId", 2);
cmd.Parameters.AddWithValue("#UserId", newUserId);
cmd.Parameters.AddWithValue("#FriendlyName", DBNull.Value);
cmd.Parameters.AddWithValue("#LastUpdated", DateTime.Now);
cmd.Parameters.AddWithValue("#CheckDate", DateTime.Now);
cmd.ExecuteNonQuery();
}
connection.Close();
}
There are a few things fundamentally wrong here...
Can we stop using AddWithValue() already?
Storing a DateTime value as a string is a bad idea. Store data as data. Then format it for display when you need to display it. A DateTime is natively understood by the system, easily sortable, can be used to perform date calculations, etc. A string is just text. (The format you have is coincidentally sortable, but deliberate management of data is always better than something that coincidentally works.)
Having said that...
You can use .ToString() to format your DateTime. For example:
cmd.Parameters.AddWithValue("#LastUpdated", DateTime.Now.ToString("yyyy-MM-dd"));
Or, if you want single-digit months/days:
cmd.Parameters.AddWithValue("#LastUpdated", DateTime.Now.ToString("yyyy-M-d"));
Basically, since you're storing a string, you need to send the database a string. Not a DateTime.
(But, again, you should be storing a DateTime and formatting it as a string when using it downstream.)

DateTime is not saving correct Date and Time in PHPMyadmin database field with"DateTime" data type

I have DateTimePicker object in a C# winform application, from which I am getting date and time in yyyy-MM-dd HH:mm tt custom format. But whenever I save the data in phpmyadmin, it gets saved as "0000-00-00 00:00:00.000000" in the specific field. My code is bellow:-
private void submit_Click(object sender, EventArgs e)
{
DateTime scd = MydateTimePicker.Value;
cn.Open();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into flight(flight_schedule) values ('" + scd + "')";
cmd.ExecuteNonQuery();
cn.Close();
}
In c# when you use a DateTime variable in a string context, it is treated as if it were appended with .ToString(). Unfortunately that delivers a locale-specific rendering of the date. On my USA locale it looks like this:
2/26/2016 7:12:19 PM
MySQL, when you present datetime values to it as strings, needs this format.
2016-02-26 19:12:19
In some versions of MySQL, a failure to interpret a date results in a zero date. Read this for more information on that topic. http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_allow_invalid_dates
Your insert query constructs a query string, so your DateTime value gets formatted in a way that MySQL cannot use. That's why you get that strange zero date.
If you changed your insert query to this, things would probably start to work.
cmd.CommandText = "insert into flight(flight_schedule) values ('" +
scd.ToString("yyyy-MM-dd HH:mm:ss") + "')";
Better yet, use parameters. Read this for an example and discussion. C# SqlParameters Short Hand
No.
You have a bad habit to kick as choosing wrong data type. You should never store your DateTime values as a string.
Change your flight_schedule to DATETIME column type and pass your DateTime value directly with a parameterized query.
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
using(var cn = new MySqlConnection(conString))
using(var cmd = cn.CreateCommand())
{
cmd.CommandText = "insert into flight(flight_schedule) values (#date)";
cmd.Parameters.Add("#date", MySqlDbType.Datetime).Value = MydateTimePicker.Value;
// I assume you change your column type to Datetime
cn.Open();
cmd.ExecuteNonQuery();
}
EDIT:
Looks like you already have DATETIME column in your database, so my answer seems irrelevant but I still believe saving your DateTime as their values, not their string representations.

Error conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I am inserting date into database, and I get this error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
My database is like
column datatype
-----------------
id int
date datetime
My current date format is DD/MM/YYYY. but it didn't accept. When I changed format (made changes in system calender not in programming) to YYYY/DD/MM, it works.
Why does the above format not work?
My query is
cmd = new SqlCommand("insert into tblnewaccount values ('" + id + "','" + dateTimePicker1.Text + "')", con);
cmd.ExecuteNonQuery();
Why does the above format not work?
I honestly don't care and neither you should. Because you are doing something terribly wrong here than using the right format.
You try to save your DateTime values with their string representation in a datetime typed column. You should always choose the right data type for your values.
Bad habits to kick : choosing the wrong data type
First, don't use Text property of your DateTimePicker, use Value property to get the value as a DateTime. And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
using(var con = new SqlConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"insert into tblnewaccount
values (#id, #date)";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("#date", SqlDbType.DateTime).Value = dateTimePicker1.Value;
con.Open();
cmd.ExecuteNonQuery();
}
It wont work because it will be recognized as a string instead of a valid DateTime object value. You can try converting it to a valid datetime format so that it can recognize it. Also, you can show the text value as dd/MM/yyyy like you are showing now, but pass the value parameter in your query if it gives you a proper datetime format.
Have a look into Conversion from string to datetime as well. That will give you clear idea in this case.
Hope this helps.

Converting data entered by user to date

I'm trying to insert data of type 'date' from a textbox on my form to the database.
I want to ensure data entered by the user is stored in the format'dd/mm/yyyy' in the database. I have a column in the database of type 'date' but when i enter values of the format above, i get an exception (something like: cannot implicitly convert varchar to type date).
Please how do I convert date entered to the format 'dd/mm/yyyy'. I tried using CONVERT((varchar,getdate(),103) AS [DD/MM/YYYY]) but i cant figure out where to place it in my code. I'm new to c# and sql server, help please!!
It's better to not convert the date in SQL, and just pass it back as a date, and then within C# you can structure it however you want
myDate.ToString("dd/mm/yyyy")
use parameterised queries:
DateTime dt;
dt = DateTime.ParseExact(TextBox1.Text,
"dd/MM/yyyy",CultureInfo.InvariantCulture);
SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "INSERT INTO [TABLENAME](DateCol) VALUES(#DateValue)";
SqlCommand cmd=new SqlCommand(query,con);
cmd.Parameters.AddWithValue("#DateValue",dt);
con.Open();
cmd.ExecuteNonQuery();
EDIT: from your comments :
i want the date to also be displayed in the same 'dd/MM/yyyy' format
in the database
You can can not control underlying Database how it displays or manages your Date in Database but if you want to get the date in format of dd/MM/yyyy while reading from database you can try the below:
SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "SELECT [DateCol] FROM TABLENAME]";
SqlCommand cmd=new SqlCommand(query,con);
con.Open();
SqlReader reader = cmd.ExecuteReader();
while(reader.Read())
{
DateTime dt= Convert.ToDateTime(reader["DateCol"].ToString());
string mydateString = dt.ToString("dd/MM/yyyy");
}
con.Close();

how to insert a datepicker datetime value into sql database

My SQL Server 2008 database has a table with a column of datatype datetime.
When I try to insert values into the datetime column I am getting error.
Incorrect syntax near '-'
My datetime picker has custom format yyyy-MM-dd e.g (2012-11-01)
Following is the code sample I used to insert datetime.
System.DateTime myDate = default(System.DateTime);
myDate = DateTimePickerPrint.Value;
string query = string.Format("EXEC Save_Quotation_Bookshop '" + txt_QutationNo.Text + "','" + txt_CusCode.Text + "',#" + myDate + "#,");
Please any one have an idea ?
First off: STOP concatenating together your SQL code! This is an invitation for SQL injection attacks, and it's really bad for performance, too - use parametrized queries instead.
If you do - you won't have the problem of datetime/string conversion issues, either.....
Secondly: the "safe" format for a date-only DateTime in SQL Server is YYYYMMDD - without any dashes - only this format guarantees that it'll run on any SQL Server, regardless of your language, regional and dateformat settings.
Thirdly. if you want to execute a stored procedure - I would recommend using this approach:
System.DateTime myDate = default(System.DateTime);
myDate = DateTimePickerPrint.Value;
using (SqlConnection con = new SqlConnection(your-connection-string-here))
using (SqlCommand cmd = new SqlCommand("dbo.Save_Quotation_Bookshop", con))
{
// tell ADO.NET it's a stored procedure (not inline SQL statements)
cmd.CommandType = CommandType.StoredProcedure;
// define parameters
cmd.Parameters.Add("#QuotationNo", SqlDbType.VarChar, 50).Value = txt_QutationNo.Text;
cmd.Parameters.Add("#CustomerCode", SqlDbtype.VarChar, 25).Value = txt_CusCode.Text;
cmd.Parameters.Add("#SaleDate", SqlDbType.DataTime).Value = myDate;
// open connection, execute stored procedure, close connection again
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Don't use EXEC ...... as an inline SQL statement - tell ADO.NET that you're executing a stored procedure, supply the parameters - and you're done!
Wrap the date in single quotes instead of #.
This string concatenation is a SQL injection waiting to happen. Use SqlCommand with parameters instead, then you don't have to worry about string conversion issues
Try this
string query = String.Format("EXEC Save_Quotation_Bookshop '{0}','{1}','{2}'",txt_QutationNo.Text,txt_CusCode.Text, myDate);
OR
string query = string.Format("EXEC Save_Quotation_Bookshop #QutationNo,#CusCode,#myDate");
...
comm.Parameters.AddWithValue("#QutationNo", txt_QutationNo.Text);
comm.Parameters.AddWithValue("#CusCode", txt_CusCode.Text);
comm.Parameters.AddWithValue("#myDate", myDate);

Categories

Resources