如何在SQL数据库的datetime类型字段中插入DateTime.Now值 [英] how to insert DateTime.Now values into datetime type field in sql database

查看:540
本文介绍了如何在SQL数据库的datetime类型字段中插入DateTime.Now值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是:

    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!";

我可以将evry类型值插入数据库。但是我不能插入 datetime .now datetime.now.addday(21)到此数据库中。键入值 date1 AND date2 是日期时间。

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.

推荐答案

您应该使用参数化查询。

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));

最好插入所有值,而不仅仅是使用参数的DateTime。不要使用字符串串联来编写SQL。

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.

这篇关于如何在SQL数据库的datetime类型字段中插入DateTime.Now值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆