I’m trying to store a datetime into a SQL database. I use datetime2(0) variable for that purpose.
But i always get this exception :
Conversion failed when converting date and/or time from character
string
Here’s my code that generates the error :
protected void InsertDB(string title, string desc, string cat, string path)
{
string now = DateTime.Now.ToString("dd-MM-yyyy h:mm:ss tt");
title = title.Length == 0 ? "Untitled" : title;
cat = cat.Length == 0 ? "Uncategorized" : cat;
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
try
{
SqlCommand cmd = new SqlCommand(@"INSERT INTO gallery (img_title, img_desc, img_cat, img_date, img_path)
VALUES (@title, @desc, @cat, @date, @path)", con);
con.Open();
cmd.Parameters.AddWithValue("@title", title.Trim());
cmd.Parameters.AddWithValue("@desc", desc.Trim());
cmd.Parameters.AddWithValue("@cat", cat.Trim());
cmd.Parameters.AddWithValue("@date", now.Trim());
cmd.Parameters.AddWithValue("@path", path.Trim());
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
msg_lbl.Visible = true;
msg_lbl.Text = "New Image is uploaded.";
title_txt.Text = "";
desc_txt.Text = "";
cat_txt.Text = "";
}
else
{
msg_lbl.Visible = true;
msg_lbl.Text = "Error occured.";
}
}
catch (SqlException ex)
{
msg_lbl.Visible = true;
msg_lbl.Text = ex.Message; //I get this exception here
}
catch (Exception ex)
{
msg_lbl.Visible = true;
msg_lbl.Text = ex.Message;
}
}
The error must be when passing the variable “now” in the sql query. If the column
Img_dateis a datetime field then you must pass the value as a a datetime not as a string. Try assigning the valueDatetime.Nowto the parameter@date: