【问题标题】:Winforms using SQL Server 2008使用 SQL Server 2008 的 Winforms
【发布时间】:2014-03-12 03:26:44
【问题描述】:
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 数据类型导致值超出范围。

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

【问题讨论】:

  • 检查您的 Date 字段,如果它确实是 Date/Time 数据类型或 varchar,如错误所建议的那样。
  • 按照 Szymon 的建议使用参数

标签: c# sql sql-server winforms


【解决方案1】:

您应该使用参数而不是连接字符串。它不仅可以消除日期格式的问题,还可以保护您免受 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;

【讨论】:

    【解决方案2】:

    如果要存储当前日期,请使用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 注入攻击,因此我建议您使用参数化查询来避免它们。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-23
        • 1970-01-01
        相关资源
        最近更新 更多