winforms1 C# using sql server 2008

本文关键字:server 2008 sql using winforms1 | 更新日期: 2023-09-27 17:49:32

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

我在数据库中使用这个代码,我的日期有datetime数据类型,但当我通过表单保存数据时,它显示

将varchar数据类型转换为日期时间数据类型导致值超出范围。语句已被终止

是什么问题?为什么会出现这个错误?

winforms1 C# using sql server 2008

使用sql的getdate()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);

建议:您的查询是开放的sql注入攻击,所以我建议您使用参数化查询来避免它们。