[英]inserting Date Time to sql server 2008 using c#
I get failed to convert parameter value from a string to a datetime
error, I have a text box in which the user should insert a date, my code is: 我
failed to convert parameter value from a string to a datetime
错误,我有一个文本框,用户应在其中插入日期,我的代码是:
SqlConnection Con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\targil3.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlDataAdapter adapt = new SqlDataAdapter();
adapt.InsertCommand = new SqlCommand("INSERT INTO tblEmployee VALUES (@employeeNumber, @employeePrivateName, @employeeFamilyName ,@city, @street, @houseNo, @phoneNumber, @birthDate, @startWorkingDate)", Con);
adapt.InsertCommand.Parameters.Add("@employeeNumber", SqlDbType.VarChar).Value = textBox1.Text;
adapt.InsertCommand.Parameters.Add("@employeePrivateName", SqlDbType.VarChar).Value = textBox2.Text;
adapt.InsertCommand.Parameters.Add("@employeeFamilyName", SqlDbType.VarChar).Value = textBox3.Text;
adapt.InsertCommand.Parameters.Add("@city", SqlDbType.VarChar).Value = textBox4.Text;
adapt.InsertCommand.Parameters.Add("@street", SqlDbType.VarChar).Value = textBox5.Text;
adapt.InsertCommand.Parameters.Add("@houseNo", SqlDbType.Int).Value = textBox6.Text;
adapt.InsertCommand.Parameters.Add("@phoneNumber", SqlDbType.VarChar).Value = textBox7.Text;
adapt.InsertCommand.Parameters.Add("@birthDate", SqlDbType.DateTime).Value = textBox8.Text;
adapt.InsertCommand.Parameters.Add("@startWorkingDate", SqlDbType.DateTime).Value = textBox9.Text;
Con.Open();
adapt.InsertCommand.ExecuteNonQuery();
Con.Close();
How do I get it to work? 我如何让它工作?
I guess the problem is here: 我想问题出在这里:
adapt.InsertCommand.Parameters.Add("@birthDate", SqlDbType.DateTime).Value = textBox8.Text;
You are specifying type to be of DateTime
type and you are passing it a string. 您将类型指定为
DateTime
类型,并且您将其传递给字符串。 Try converting your string value to DateTime
type object like: 尝试将您的字符串值转换为
DateTime
类型对象,如:
adapt.InsertCommand.Parameters.Add("@birthDate", SqlDbType.DateTime).Value
= Convert.ToDateTime(textBox8.Text);
You may look into DateTime.ParseExact
or DateTime.TryParseExact
, if you get format exception during parsing. 如果在解析过程中遇到格式异常,则可以查看
DateTime.ParseExact
或DateTime.TryParseExact
。 See: Customized DateTime Formats . 请参阅: 自定义日期时间格式 。
you could ideally set the adapt.InsertCommand to a variable and use it instead (both perf. and less typing) 你可以理想地将adapt.InsertCommand设置为一个变量并改为使用它(包括perf和更少的输入)
assuming you guaranty the correct format for the text of textbox, change the lines with datetime parameters like this 假设您保证文本框文本的正确格式,请使用datetime参数更改这样的行
adapt.InsertCommand.Parameters.Add("@birthDate", SqlDbType.DateTime).Value = DateTime.Parse(textBox8.Text, "yyyy/MM/dd");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.