Converting data entered by user to date - c#

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

Related

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

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

Error while inserting date from textbox in asp.net

I am new to C#, and learning. I have a SQL Server database where I have table record that has a column dob of data type date. I am trying to insert into dob from my textbox which has a value of 19-08-17 with the following code
datebox.Text = "19-08-17";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", datebox.Text);
com.ExecuteNonQuery();
But I get this error
Conversion failed when converting date and/or time from character string.
How can I solve this?
When you pass a variable to a DateTime column as a parameter, you need to convert the text to a DateTime variable before passing it:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].Connect ionString);
// Convert the textbox text to a DateTime variable
DateTime myDate = DateTime.ParseExact(datebox.Text, "dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", myDate);
com.ExecuteNonQuery();

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.

Retrieving data from sqlite on the basis of date

I am retrieving data from Sqlite database using the following query in c#
SELECT * FROM tableName
It works fine. But I want to retrieve data on the basis of date like:
SELECT * FROM tableName WHERE date=09-09-2013
But it do not works for me because Sqlite date representation is not in this date format.
What i want to ask is that is there any method by which Sqlite data can be retrieved on the basis of user date and time like mentioned in above query and how can I represent date and time of Sqlite database in user readable format.
A parameterized query would free your code from the formatting required for date, strings and decimals by various database engines
using (SqliteConnection con = new SqliteConnection(connectionString))
{
con.Open();
string commandText = "SELECT * FROM tableName WHERE date=#dt";
using (SqliteCommand cmd = new SqliteCommand(commandText, con))
{
cmd.Parameters.AddWithValue("#dt", yourDateVariable)
SqliteReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// Extract your data from the reader here
.....
}
}
}
The point of this example is to show how to build a parameterized query. In this way you pass the value of your datetime variable to the framework of Sqlite engine that knows better how to format a date for the underlying system.
In the commandText variable the actual formatted value for the date is taken by the placeholder #dt, then add, to the SqliteCommand Parameters collection, a parameter with the same name of the placeholder and the value from your date variable.

Categories

Resources