asp.net - Insert datetime from C# into SQL Server database -
when try insert datetime
value sql server database error:
conversion failed when converting date and/or time character string
code:
connection.open(); sqlcommand command = new sqlcommand("insert table values(@time)", connection); command.parameters.addwithvalue("@time", datetime.now); command.executenonquery(); connection.close();
table table
has 1 datetime
column called time
.
edit:
table created in mssql 2012: http://i.imgur.com/tj3t3y7.png
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 otazky values('" + id + "', '" + uzivatel + "', '0','0','0','@cas','" + nazev + "','" + dotaz + "')", connection); command.parameters.addwithvalue("@cas", datetime.now); command.executenonquery(); connection.close(); }
the actual problem here you're writing parameter inside quotes:
... ,'0','@cas',' ... ^ ^
this not use @cas parameter, you're trying insert string "@cas" column, not contents of parameter @cas.
remove quotes , part should work.
additionally, don't use string concatenation build sql, use parameters everything, save headache sql injection attacks or quotes or whatnot. related "id", "uzivatel", "nazev", , "dotav" parameters you're using (method parameters is).
Comments
Post a Comment