我的代码是:
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!";
我可以将每个类型的值插入到数据库中。但是我无法将datetime.now
或datetime.now.addday(21)
插入此数据库.type values date1
和date2
是datetime。
答案 0 :(得分:1)
您应该使用参数化查询。
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));
最好插入所有值,而不只是使用参数插入DateTime。不要使用字符串连接来编写SQL。