如何使用dateTimePicker将日期插入sql db日期列? [英] How to INSERT date into sql db date column using dateTimePicker?
问题描述
Hello All,
我的问题很简单我的sql中有一个类型为 date
的生日列数据库和我的应用程序我使用dateTimePicker来获取生日,但是当我尝试插入dateTimePicker的日期时,我得到一个错误'12'附近的语法错误
当我尝试调试代码时,我发现从dateTimePicker得到的值是Date = {7/16/2011 12:00:00 AM}
代码:
Hello All,
My problem is simple I have a birthdate column of type date
in my sql database and in my application I use dateTimePicker to get the birthdate, but when trying to insert the date I got from the dateTimePicker I get an error Incorrect syntax near '12'
And when I try to debug the code I find that the value I get from the dateTimePicker is Date = {7/16/2011 12:00:00 AM}
the CODE:
//cmd is sql command
cmd.CommandText="INSERT INTO person (birthdate) VALUES("+dateTimePicker.Value.Date+")";
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
提前付款
: - )
Thanks in advance
:-)
推荐答案
您应该使用参数添加日期。你从上面snipet应该如下所示
you should add your date using a parameter. you snipet from above should look like below
cmd.CommandText = "INSERT INTO person (birthdate) VALUES(@date)";
cmd.Parameters.Add(new SqlParameter("@date", dateTimePicker.Value.Date));
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
帮助参数
http://g4ac.co.za/WFU4g [ ^ ]
由于您使用的日期的数据类型仅为Date
并且你的datepicker值返回时间
以及日期。
将数据类型更改为datetime
和/或只传递Date值以插入。
As the datatype for the date you used is onlyDate
and your datepicker value is returningTime
along with date.
Either change the datatype todatetime
and or pass only Date value to insert.
我解决问题的方法是将SQL DB中的数据类型更改为VARCHAR(50)
并在代码中执行以下SQL查询。
I way to solve the problem would be to change the data type in the SQL DB to VARCHAR(50)
and the execute the following SQL query in your code.
con.Open();
cmd.CommandText = "INSERT INTO dbo.Person (birthdate) VALUES ('" + this.dateTimePicker.Text + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
这将在SQL DB中显示2011年7月16日的值而没有时间值。然后可以使用以下内容将其转换为短日期字符串
This will display the value as 16 July 2011 in your SQL DB without the time value. This can then be converted to to a short date string be using the following
string dateString = this.dateTimePicker1.Text;
DateTime Date = Convert.ToDateTime(dateString.ToString());
然后您可以将日期输出为短日期格式使用以下内容;
You can then output the date to a short date format using the following;
MessageBox.Show(Date.ToShortDateString());
希望这会有所帮助。
编辑
--------- ----------------------------------------------
使用Sql参数来避免 SQL注入 [ ^ ]。
输入SQL Server的DateTime列的空值 [ ^ ](解释如何传递val使用sql参数。)
Hope this helps.
EDIT
-------------------------------------------------------
Use Sql parameters to avoid SQL injection[^].
Enter Null Values for DateTime Column of SQL Server[^](Explains how to pass values using sql parameters.)
这篇关于如何使用dateTimePicker将日期插入sql db日期列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!