错误无法将参数值从String转换为DateTime。 [英] Error Failed to convert parameter value from a String to a DateTime.

查看:460
本文介绍了错误无法将参数值从String转换为DateTime。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,





我收到错误将参数值从String转换为DateTime失败。



在下面的场景中我收到了这个错误。



当我在本地机器上进行单元测试时然后它工作正常。

在我的本地机器上没有这样的错误操作系统是windows7,但是当我在服务器上部署代码然后我得到了这个错误,在服务器上有windows8,
是否存在一些文化问题,因此抛出此错误。



以下可能性我已经检查过,由于此错误可能会发生:



我检查了服务器系统日期时间和我的机器日期时间,它是一样的,

更改了日期格式,如MM / DD / YYYY。



以下代码我使用:



Hi everyone ,


I got Error Failed to convert parameter value from a String to a DateTime.

In Below Scenario I got this error.

when I am doing Unit testing on my Local Machine then it is working fine.
there is no error like this on my local machine OS is windows7, but when I deploy code on Server then I got this Error , on server there is windows8 ,
IS there some culture issue due to which throw this ERROR.

Below possibilities I have checked that due to this error may be occurred :

I have check Server system datetime and my machine datetime , it is same,
changed date format like MM/DD/YYYY.

Below Code I m using :

SqlParameter[] parms1 = {
            new SqlParameter("@VisitDate", SqlDbType.Date)
            };
           parms1[0].Value = DateTime.Now.Date;









但服务器上发生错误。



建议我做什么来解决这个问题..







先谢谢了。





~MP





but error is occurring on Server.

suggest me what I do for resolving this issue..



Thanks in advanced.


~MP

推荐答案

首先不要连接字符串以形成SQL命令:改为使用参数化查询。 br />
连接字符串是非常危险的 - 它让你对SQL注入很开放,这很容易损坏或破坏你的数据库。



然后检查值,并将它们在C#(当您有权访问用户文化信息时)转换为适当的数据类型并通过它:将有效的日期时间和数字信息传递给SQL而不是字符串表示意味着没有转换SQL来执行此操作错误消失。



如果你传递数据es作为字符串,然后你离开SQL来猜测用户输入的日期格式:是dd / mm / yy还是mm / dd / yy?还是yy / mm / dd?或者像32/3/1997这样的无效数据?或者用户输入你好?所有这些都可能导致SQL抛出异常,应该尽早捕获并返回给用户进行更正。 SQL不能这样做。
Start off by not concatenating strings to form SQL commands: use parametrized queries instead.
Concatenating strings is very dangerous - it leave you wide open to SQL Injection which can easily damage or destroy your database.

Then check the values, and convert them in C# (when you have access to the user culture info) to an appropriate datatype and pass that through: passing valid datetime and numeric information to SQL instead of a string representation means there is no conversion for SQL to do so the error goes away.

If you pass dates as strings, then you leave SQL to guess what date format the user entered it in: was it dd/mm/yy or mm/dd/yy? Or yy/mm/dd? Or an invalid data like 32/3/1997? Or did the user type "hello"? All of these can cause SQL to throw an exception, and should be caught as early as possible and refered back to the user for correction. SQL can't do that.


这篇关于错误无法将参数值从String转换为DateTime。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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