字符串未被识别为有效的DateTime。 [英] String was not recognized as a valid DateTime.?

查看:95
本文介绍了字符串未被识别为有效的DateTime。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi


我试图将记录保存到表格中任何人都可以告诉我我的代码到底有什么问题



我的系统日期时间格式

hi
am trying to save records to table can any one tel me what exactly problem with my code

my system date time format

dd-MM-yyyy





sql tbl_agreement1







sql tbl_agreement1


ID	int	Unchecked
Party1	nvarchar(50)	Checked
Party1ADD	nvarchar(50)	Checked
Party2	nvarchar(50)	Checked
Party2add	nvarchar(50)
Capacity	nvarchar(50)	
Agper	nvarchar(50)	
AGtop	nvarchar(50)	
AGplace	nvarchar(50)	
Tnco	nvarchar(50)	
Status	nvarchar(50)	
Endno	nvarchar(50)	
Mulahiq	varchar(50)	
Qarar	nvarchar(50)	
entered	nvarchar(MAX)	
username	nvarchar(MAX)	
[update]	nvarchar(MAX)	
[last update date]	datetime2(0)	
laspusername	nvarchar(MAX)	
[entered-date]	datetime2(0)	
AGend	datetime	
AGdt	datetime	
Enddt	datetime	





/ /按钮点击



//button click

 protected void Button2_Click(object sender, EventArgs e)
    {
        string dt = DateTime.Now.ToShortDateString();
        
        try
        {

            DAL.InsertAgreement3(TextBox1.Text, TextBox2.Text,TextBox3.Text,TextBox4.Text,TextBox5.Text,TextBox6.Text,TextBox7.Text,TextBox8.Text,TextBox9.Text,TextBox10.Text,TextBox12.Text,TextBox11.Text,TextBox13.Text,TextBox14.Text,TextBox15.Text,TextBox16.Text, Session["username"].ToString());
            info.Style.Add("display", "block");
            lblerror.Visible = true;
            lblerror.Text = "Successfuly Inserted Record...";

            Response.Redirect("Agreement3.aspx");
            //clearTxt();
            
        }
        catch (Exception ex)
        {
            info.Style.Add("display", "block");
            lblerror.Visible = true;
            lblerror.Text = "Error Occured while adding.....!!!!! " + " " + ex.Message;

        }
}



//DAL 

<pre>

 public static void InsertAgreement3(string Agdt, string party1, string partyadd, string party2, string party2add, string capacity, string agper, string agtop, string agplace, string Termscon, string Agend, string Status, string EndNo, string Enddate, string Mulahiq, string Qarar, string uname)
    {
        DateTime dt;
        string sdt = System.DateTime.Now.ToString();
        string sdt1 = DateTime.Now.ToShortDateString();

        SqlConnection sqlconn = new SqlConnection(ConnString);
        try
        {
            sqlconn.Open();
            string Query = "INSERT INTO [tbl_agreement1]([AGdt],[Party1],[Party1ADD],[Party2],[Party2ADD],[Capacity],[AGper],[AGtop],[AGPlace],[Tnco],[AGend],[Status],[Endno],[Enddt],[Mulahiq],[Qarar],[entered],[entered-date],[username]) VALUES (N'" + DateTime.Parse(Agdt).ToString(new CultureInfo("en-US")) + "',N'" + party1 + "',N'" + partyadd + "',N'" + party2 + "',N'" + party2add + "',N'" + capacity + "',N'" + agper + "',N'" + agtop + "',N'" + agplace + "',N'" + Termscon + "',N'" + DateTime.Parse(Agend).ToString(new CultureInfo("en-US")) + "',N'" + Status + "',N'" + EndNo + "',N'" + DateTime.Parse(Enddate).ToString(new CultureInfo("en-US")) + "',N'" + Mulahiq + "',N'" + Qarar + "',N'" + "New Record Added" + "',N'" + DateTime.Parse(sdt).ToString(new CultureInfo("en-US")) + "',N'" + uname + "' )";
            SqlCommand sqlcomm = new SqlCommand(Query, sqlconn);
            sqlcomm.ExecuteNonQuery();
        }
        catch (Exception ex)//getting error here
        {

        }
        finally
        {
            sqlconn.Close();
        }











可以任何人建议我这个不能保存记录...



谢谢...






can any one suggest me for this m not able to save records...

thank you...

推荐答案

您的系统日期/时间格式设置为什么并不重要:SQL通常使用ISO标准yyyy-MM-dd,因此您的系统设置无关紧要,特别是如果这是一个基于Web的应用程序作为ASP你问题标签的.NET部分暗示 - cleint可能完全使用不同的系统,你应该知道这一点。



现在,让我们尝试修复它有点......按重要性排序:



首先要做的事情:不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。改为使用参数化查询。



第二件事:为什么要将字符串解析为日期时间,以便将其转换为(可能不同的)字符串并传递它到SQL需要再次转换回DateTime值吗?相反,使用参数化查询,并直接将DateTime值作为DateTime传递 - 这样,SQL将始终理解它,并且您的问题部分消失。



第三:为什么你从DateTime值开始,将它转换为再次获取它的字符串(并希望它不是午夜或之后都会崩溃),然后在第二点将其转换回DataTime?读一次当前时间。而且只有一次。将它存储在DateTime中,并将其作为DateTime传递给SQL。



第四:在输入到达之前验证您的输入:将用户输入的Enddate值转换为DateTime当他输入它,并在那里报告问题而不是将错误的格式日期字符串传递给代码这么深 - 你不能直接报告问题,因为你不知道期望的UI(如果有的话)。因此,尽早转换它,并将DateTime值传递给圆形,而不是字符串。
It doesn't matter what your systems date/time format is set to: SQL normally uses ISO standard yyyy-MM-dd so your system setting is irrelevant, particularly if this is a web based application as the ASP.NET part of you question tags implies - the cleint may well be using a different system altogether, and you should be aware of that.

Now, lets try to fix it a bit...in order of importance:

First things first: Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

Second thing: Why the heck are you parsing a string to a datetime, in order to convert it to a (possibly different) string and pass it to SQL where it needs to be converted back into a DateTime value again? Instead, use a parametrized query, and pass the DateTime value directly as a DateTime - that way, SQL will always understand it, and you problem partly disappears.

Thirdly: Why are you starting with a DateTime value, converting it to a string getting it again (and hoping it wasn't midnight or it all falls apart later) and then converting it back to a DataTime at the second point? Read the current time once. And once only. Stor it in a DateTime, and pass it to SQL as a DateTime.

Fourthly: Validate your inputs before they get here: convert the user entered Enddate value to a DateTime when he inputs it, and report problems there instead of passing a bad format date string through to code this deep - where you can't report a problem directly because you don't know what UI to expect (if any). So convert it as early as possible, and pass DateTime values round, rather than strings.


这篇关于字符串未被识别为有效的DateTime。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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