问题
my code is :
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=haftehbazardb;Integrated Security=True ");
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = string.Format("Insert into Table_test(date1,date2) Values({0},{1})", DateTime.Now, DateTime.Now.AddDays(21));
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
Label1.Text = "Insert is done successfuly!";
I can insert evry type values into database.but i can not insert datetime.now or datetime.now.addday(21) into this database.type values date1 AND date2 is datetime.
回答1:
You should be using parameterized queries.
cmd.CommandText = "Insert into Table_test(date1,date2) Values(@Now,@21DaysLater)";
cmd.Parameters.AddWithValue("@Now", DateTime.Now);
cmd.Parameters.AddWithValue("@21DaysLater", DateTime.Now.AddDays(21));
It would be a good idea to insert all of your values, not just DateTime using parameters. Don't use string concatenation to write SQL.
来源:https://stackoverflow.com/questions/27400750/how-to-insert-datetime-now-values-into-datetime-type-field-in-sql-database