简体   繁体   English

将datetimepicker值插入SQL Server 2008

[英]inserting datetimepicker value to SQL Server 2008

I'm trying to insert a value from a datetimepicker value to a SQL Server table. 我正在尝试将datetimepicker值中的值插入SQL Server表中。

My table looks like this 我的桌子看起来像这样

Profile (Id, Name,..., DateofBirth(date)...)

I have tried this to convert datetime picker value to 我已经尝试过将日期时间选择器值转换为

string dt = dateTimePicker.Value.ToString("yyyy-mm-dd hh:MM:ss");

Insert into profile (id, DateofBirth)  
values(id,  CONVERT(datetime, CONVERT( varchar(11), dt, 101));

also use this 也用这个

var date = new DateTime(dateTimePickerText);

also use this 也用这个

DateTime date = DateBox.Value.Date;
string sDate = date.ToString("dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture);
DateTime dateInsert = Convert.ToDateTime(sDate); 

but can't able to insert the date into the database. 但无法将日期插入数据库中。 2nd how can I retrieve back the date from database? 2如何从数据库中检索日期?

You must have to use SqlParameter . 您必须使用SqlParameter

 sql="Insert into profile (id, DateofBirth) values (@id,@DateofBirth)";
    using(SqlCommand cmd=new SqlCommand(sql,conn))
     {
        cmd.Parameters.Add("@id",SqlDbType.Int).Value=10;
        cmd.Parameters.Add("@DateofBirth",SqlDbType.DateTime).Value=dateTimePicker.Value;

        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
     }

Personally I'd get into the habit of using parameters for all of your SQL queries. 就个人而言,我会养成对所有SQL查询使用参数的习惯。 That way you avoid SQL injection attack vector and you can also specify the parameter type as datetime. 这样,您可以避免SQL注入攻击向量,还可以将参数类型指定为datetime。 See this answer for example. 例如,请参见此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM