Dastry Dastry - 2 months ago 16
ASP.NET (C#) Question

Error inserting date value to database

I am receiving the following error when trying to enter a date into a date column in my sql database table:


Conversion failed when converting date and/or time from character string.


Date
is a DateTime variable passed from asp.net calendar control

string sql = "INSERT INTO [Meals] ([Date]) VALUES ('@Date')";

using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
var formatedDate = date.ToString("yyyy-MM-dd");

SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Date", formatedDate);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}


Meals
is the table name and
Date
is the column of type
date
that can be null.

I have tried passing DateTime.Now and variations and it still yields the same error. I have tried entering a manual date and DateTime.ParseExact.

Answer
string sql = "INSERT INTO [Meals] ([Date]) VALUES (@Date)";

Just remove single quotes in @Date parameter