繁体   English   中英

使用SQL Server 2008的Winforms

[英]Winforms using SQL Server 2008

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数据类型到datetime数据类型的转换导致值超出范围。

怎么了 为什么会显示此错误?

您应该使用参数而不是连接字符串。 它不仅可以消除日期格式的问题,而且还可以防止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注入攻击开放,所以我建议您使用Paramterised Queries以避免它们。

连接sql字符串时,您需要附加日期字符串,而不是datetime变量。 因此,除非您有其他原因将当前变量设置为日期,否则将其设置为字符串。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM