Reputation: 283
I have a date in textBox like 2014-17-04 i.e.(YYYY-DD-MM) I wnt to put it in the database such as 2014-04-17 00:00:00 ,So How can I do this. I have tried like following..
sSQL = "INSERT INTO Date_Master(BirthDate) VALUES('"+Convert.ToDateTime(txtBirthdate.Text)+"')";
but it gives error that "String was not recognized as a valid DateTime" . So how can I insert values in the database using MySQL DATE_FORMAT?
Upvotes: 0
Views: 1045
Reputation: 25370
Use DateTime TryParse or TryParseExact to test your input
DateTime dt;
if (DateTime.TryParseExact(txtBirthdate.Text, "yyyy-dd-MM", CultureInfo.InvariantCulture, DateTimeStyles.None,out dt))
{
var insert = "INSERT INTO Date_Master(BirthDate) VALUES(@birthdate)";
using (SqlCommand cmd = new SqlCommand(insert, yourConnection))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@birthdate",dt);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
yyyy-dd-MM
matches your expected input. And as @JonSkeet added, always use parameterized queries to avoid injection
Upvotes: 1