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

请帮我从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(); 

并且它抛出一个exception说: – 从字符串转换日期和/或时间时转换失败。

您需要根据您的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); 

要么

日期格式字符串

 // String to DateTime String MyString; MyString = "1999-09-01 21:34 PM"; //MyString = "1999-09-01 21:34 pm"; //Depends on your regional settings DateTime MyDateTime; MyDateTime = new DateTime(); MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null); 

使用Paramerize查询以避免SQL INJECTION …使代码更少错误代码演练:使用参数化查询在Windows窗体中显示数据

请注意 – 您需要清理该查询以防止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字符串。

  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();