winforms1 C#使用sql server 2008
我在数据库中使用此代码,我的日期具有datetime数据类型,但当我通过显示的表单保存数据时 将varchar数据类型转换为datetime数据类型导致值超出范围。声明已被终止 问题是什么?显示此错误的原因?如果要存储当前日期,请使用sql的winforms1 C#使用sql server 2008,c#,sql-server,date,datetime,C#,Sql Server,Date,Datetime,我在数据库中使用此代码,我的日期具有datetime数据类型,但当我通过显示的表单保存数据时 将varchar数据类型转换为datetime数据类型导致值超出范围。声明已被终止 问题是什么?显示此错误的原因?如果要存储当前日期,请使用sql的getdate()或SYSDATETIME()函数 试试这个: con = new SqlConnection(cs); con.Open(); DateTime current = DateTime.Now; current = Convert.ToDat
getdate()
或SYSDATETIME()
函数
试试这个:
con = new SqlConnection(cs);
con.Open();
DateTime current = DateTime.Now;
current = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"));
SqlCommand cmd = new SqlCommand(@"INSERT INTO CustomerDetails
(CustomerId, Date, Name, Gender, Address, Phone, Email, MobileNo,Notes)
VALUES ('" + txtCustomerID.Text + "','" + current + "','" +
txtCustomerName.Text + "','"+Gender+"','"+txtAddress.Text+"','" + txtPhone.Text
+ "','" + txtEmail.Text+"','" + txtMobileNo.Text + "','" +txtNotes.Text + "')",
con);
cmd.ExecuteNonQuery();
con.Close();
建议:您的查询容易受到sql注入攻击,因此我建议您使用参数化查询来避免这些攻击。您的问题是什么?我不明白为什么这个问题会被关闭!虽然它是有效的。@user3327117:不要将日期转换为字符串,直接存储
DateTime。现在
。它在我的朋友电脑上工作,但在我的电脑上不工作,所以有什么问题吗?或者为了更精确。在哪里使用SysDatetime()请检查我上面的答案
SqlCommand cmd = new SqlCommand(@"INSERT INTO CustomerDetails
(CustomerId, Date, Name, Gender, Address, Phone, Email, MobileNo,Notes)
VALUES ('" + txtCustomerID.Text + "',+ getdate() + ,'" +
txtCustomerName.Text + "','"+Gender+"','"+txtAddress.Text+"','" + txtPhone.Text
+ "','" + txtEmail.Text+"','" + txtMobileNo.Text + "','" +txtNotes.Text + "')",
con);