Dastry Dastry - 11 months ago 52
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.

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

is the table name and
is the column of type
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 Source
string sql = "INSERT INTO [Meals] ([Date]) VALUES (@Date)";

Just remove single quotes in @Date parameter