请帮助我将日期从文本框中以 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();
它抛出一个异常说:- 从字符串转换日期和/或时间时转换失败。
最佳答案
您需要根据您的 sql server 格式转换数据,这样您才能解决问题..
尝试
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 p.m."; //Depends on your regional settings
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
null);
使用参数化查询来避免 SQL 注入(inject)...减少代码错误 Walkthrough: Displaying Data in a Windows Form Using a Parameterized Query
关于c# - 如何将日期从文本框插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9223524/