Datepicker错误“将数据类型nvarchar转换为datetime时出错 [英] Datepicker error "error converting data type nvarchar to datetime

查看:89
本文介绍了Datepicker错误“将数据类型nvarchar转换为datetime时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想在sql server中保存日期时间时会发生这种情况



我尝试了什么:



sqlCmd.Parameters.AddWithValue(@ SmBagDatePurchased,txtPurDate.Text.Trim());

this happens when i want to save datetime in sql server

What I have tried:

sqlCmd.Parameters.AddWithValue("@SmBagDatePurchased", txtPurDate.Text.Trim());

推荐答案

简单:输入的日期当由SQL处理时,它不是有效的日期时间值。

这意味着用户输入了错误数据,或者运行的计算机SQL的设置与用户期望的设置不同。



无论哪种方式,解决方案都是相同的:将用户数据处理为DateTime值,如果有效则直接传递:

Simple: the date entered is not a valid datetime value when processed by SQL.
That means either the user entered bad data, or the settings for the computer SQL is running on are different from those the user expects.

Either way, the solution is the same: process the user data into a DateTime value and pass that directly if it is valid:
DateTime dt;
if (!DateTime.TryParse(txtPurDate.Text.Trim(), out dt))
   {
   // Bad user input - tell him what the problem is
   ...
   return;
   }
...
sqlCmd.Parameters.AddWithValue("@SmBagDatePurchased", dt);

这样,不良数据不会进入数据库,并且不存在误解基于文本的日期的风险。毕竟,什么日期是01/02/03?一旦你到达SQL Server,所有的用户上下文都会丢失,所以没有办法告诉你。



我还建议基于日期的输入更好地通过一个DateTimePicker或类似的而不是文本框,因为它不允许错误的日期,并直接为您提供DateTime值而无需转换它。

That way, bad data doesn't get into the DB, and there is no risk of misinterpretation of the text based date. After all, what date is 01/02/03? Once you reach SQL Server, all user context is lost, so there is no way to tell.

I'd also suggest that date based input is better handled via a DateTimePicker or similar rather than a text box as that doesn't allow bad dates, and gives you the DateTime value directly without any need to convert it.


这篇关于Datepicker错误“将数据类型nvarchar转换为datetime时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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