如何将日期从文本框插入数据库

时间:2012-02-10 06:12:41

标签: c# asp.net

请帮我从dd-mm-yyyy格式的文本框中插入日期到sql server。 我的代码如下: -

        int prio = Convert.ToInt32(Priority.Text);
        string stdate = planstart.Text;
        string endate= planend.Text;

        string actst = actualstart.Text;
        string acten = actualend.Text;



            SqlConnection myconnection = new SqlConnection(constring);
            SqlCommand mycommand = new SqlCommand();
            DataSet mydataset = new DataSet();
            SqlDataAdapter mydataadapter = new SqlDataAdapter();

            myconnection.Open();
            mycommand.Connection = myconnection;
            mycommand.CommandText = " insert into project_status.dbo.Project_Status_Report values('" + projectcode.Text + "','" + projectname.Text + "',(select P_Code from project_status.dbo.Project_Type where Project_Type = '" + projecttype.Text + "')," + prio + ",'" + stdate + "','" + endate + "','" + actst + "','" + acten + "','" + currentstatus.Text + "','" + remark.Text + "','no');";

            mycommand.CommandType = CommandType.Text;
            mycommand.ExecuteNonQuery();

它正在抛出异常说: - 从字符串转换日期和/或时间时转换失败。

3 个答案:

答案 0 :(得分:1)

您需要根据您的sql server formate转换数据,这样才能解决问题..

尝试

String UrDate = "27/12/2011"; 
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo(); 
dateInfo.ShortDatePattern = "dd/MM/yyyy"; 
DateTime validDate= Convert.ToDateTime(toDate, dateInfo); 

Format String For Dates

// String to DateTime
 String MyString;
 MyString = "1999-09-01 21:34 PM";
 //MyString = "1999-09-01 21:34 p.m.";  //Depends on your regional settings

 DateTime MyDateTime;
 MyDateTime = new DateTime();
 MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
                                      null);

利用Paramerize查询来避免SQL INJECTION ...使代码减少错误 Walkthrough: Displaying Data in a Windows Form Using a Parameterized Query

答案 1 :(得分:0)

请注意 - 您需要清理该查询以防止SQL注入攻击。考虑使用参数化查询。阅读它,这不是这个答案的范围。

您应首先创建强类型DateTime对象,然后按照需要插入的方式对其进行格式化。请考虑对您的代码进行以下修改:

string stdate = DateTime.Parse(planstart.Text).ToString();
string endate = DateTime.Parse(planend.Text).ToString();

string actst = DateTime.Parse(actualstart.Text).ToString();
string acten = DateTime.Parse(actualend.Text).ToString();

修改

我从ToString()中删除了字符串参数,因此您可以获得SQL Server可以使用的有效DateTime字符串。

答案 2 :(得分:0)

 con.Open();
 string query = "insert_demo";
    /* date  fromat Stored*/
 TextBox2.Text = DateTime.Now.ToLongDateString();
 SqlCommand com = new SqlCommand(query, con);


 com.CommandType = CommandType.StoredProcedure;

 com.Parameters.AddWithValue("@Name", TextBox1.Text.ToString());
 com.Parameters.AddWithValue("@Date", TextBox2.Text.ToString());

 com.ExecuteNonQuery();