Winforms using SQL Server 2008

本文关键字:2008 Server SQL using Winforms | 更新日期: 2023-09-27 17:49:41

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数据类型转换为日期时间数据类型导致值超出范围。

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

Winforms using SQL Server 2008

您应该使用参数而不是连接字符串。它不仅可以消除日期格式的问题,还可以保护您免受SQL注入。

SqlCommand cmd = new SqlCommand(@"INSERT INTO CustomerDetails
    (CustomerId, Date, Name, Gender, Address, Phone, Email, MobileNo,Notes)
     VALUES  (@CustomerId, @Date, @Email, @Mobile, @Notes)", con);
cmd.Parameters.Add("@CustomerId", SqlDbType.VarChar, 10).Value = txtCustomerID.Text;
cmd.Parameters.AddWithValue("@Date", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("@Email", SqlDbType.VarChar, 10).Value = txtEmail.Text;
cmd.Parameters.Add("@Mobile", SqlDbType.VarChar, 10).Value = txtMobileNo.Text;
cmd.Parameters.Add("@Notes", SqlDbType.VarChar, 10).Value = txtNotes.Text;

使用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注入攻击,所以我建议您使用参数化查询来避免它们。

在连接sql字符串时,需要附加日期字符串,而不是datetime变量。因此,除非你有其他原因,当前变量是一个日期,我将使它成为一个字符串。

string current = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"));