user3163265
user3163265

Reputation: 23

Inserting date in database

datofreg is of type datetime

my command is

SqlCommand cmd = new SqlCommand("insert into stud(datofreg) values('"+DateTime.Now+"'",conn);

when i execute it says Incorrect syntax near '1/6/2014 12:45:17 AM'.

Upvotes: 2

Views: 95

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98848

Your problem is you are missing ) at the end of your query but don't use this way..

"insert into stud(datofreg) values('" + DateTime.Now + "')"
                                                        ^^here

You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

For example;

SqlCommand cmd = new SqlCommand("insert into stud(datofreg) values(@date)", conn);
cmd.Parameters.AddWithValue("@date", DateTime.Now);
cmd.ExecuteNonQuery();

Upvotes: 4

Related Questions