如何将DateTime.Now值插入sql数据库中的datetime类型字段

时间:2014-12-10 12:14:24

标签: asp.net sql-server database webforms

我的代码是:

    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.nowdatetime.now.addday(21)插入此数据库.type values date1date2是datetime。

1 个答案:

答案 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。