将varchar数据类型转换为日期时间数据类型会导致超出范围的值c# [英] conversion of a varchar data type to a datetime data type resulted in an out-of-range value c#

查看:97
本文介绍了将varchar数据类型转换为日期时间数据类型会导致超出范围的值c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用datetimepicker将日期插入数据表,此特定列的数据已指定为datetime。当我运行我的项目时,我收到此错误:



将varchar数据类型转换为日期时间数据类型导致超出范围的值



这是我的sql命令:



'+ Convert.ToDateTime(MyDateTimePicker.Text)+ '

解决方案

停止这样做!为什么使用直接返回DateTime的DateTimePicker,然后依赖它生成的依赖于用户的字符串?



永远不要连接字符串以形成SQL命令 - 使用参数化而是查询。连接可以让你对SQL注入开放,这可能会破坏或破坏你的数据库 - 不是在这种情况下,但是在任何时候使用参数都是一个很好的原则。在这种情况下,你的问题也会消失:

 SqlCommand cmd =  new  SqlCommand(  INSERT INTO MyTable(myDateColumn)VALUES(@DT),con); 
cmd.Parameters.AddWithValue( @ DT,MyDateTimePicker.Value);


I am trying to insert the date into a data table using a datetimepicker, this particular column's data as been specified as datetime. When ever I run my project I get this error:

" conversion of a varchar data type to a datetime data type resulted in an out-of-range value"

Here is my sql command:

'" + Convert.ToDateTime(MyDateTimePicker.Text) + "'

解决方案

Stop doing that! Why use a DateTimePicker that returns a DateTime directly, and then rely on the user-dependant string it generates?

And never concatenate strings to form an SQL command - use parameterised queries instead. Concatenation can leave you wide open to SQL Injection which can damage or destroy your database - not in this case, but it's a good principle to use parameters at all times. In this case, you problem will go away as well:

SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (myDateColumn) VALUES (@DT)", con);
cmd.Parameters.AddWithValue("@DT", MyDateTimePicker.Value);


这篇关于将varchar数据类型转换为日期时间数据类型会导致超出范围的值c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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