Skip to content
Advertisement

Insert datetime from C# into SQL Server database

when I try to insert datetime value into a SQL Server database I get this error:

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

Code:

connection.Open();
SqlCommand command = new SqlCommand("insert into table values(@time)", connection);
command.Parameters.AddWithValue("@time", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();

Table table has 1 datetime column called time.

Edit:
my table created in msSQL 2012: http://i.imgur.com/TJ3t3y7.png
my real code is:

public void vytvorDotaz(String uzivatel, DateTime cas, String nazev, String dotaz)
    {
        int id = getMaxID() + 1;
        connection.Open();
        SqlCommand command = new SqlCommand("insert into otazky values('" + id + "', '" + uzivatel + "', '0','0','0','@cas','" + nazev + "','" + dotaz + "')", connection);
        command.Parameters.AddWithValue("@cas", DateTime.Now);
        command.ExecuteNonQuery();
        connection.Close();
    }

Advertisement

Answer

The actual problem here is that you’re writing the parameter inside quotes:

... ,'0','@cas',' ...
         ^    ^

This will not use @cas as a parameter, you’re actually trying to insert the string “@cas” into that column, not the contents of the parameter @cas.

Remove the quotes and that part should work.

Additionally, don’t use string concatenation to build up the SQL, use parameters for everything, save you some headache from SQL injection attacks or quotes or whatnot. This is related to the “id”, “uzivatel”, “nazev”, and “dotav” parameters you’re using (method parameters that is).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement