Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Winforms使用SQL Server 2008_C#_Sql_Sql Server_Winforms - Fatal编程技术网

C# Winforms使用SQL Server 2008

C# Winforms使用SQL Server 2008,c#,sql,sql-server,winforms,C#,Sql,Sql Server,Winforms,我在数据库中使用此代码我的日期具有datetimedatatype,但当我通过表单保存数据时,显示错误: 将varchar数据类型转换为datetime数据类型导致值超出范围 问题是什么?为什么会出现此错误?如果要存储当前日期,请使用sql的getdate()或SYSDATETIME()函数 试试这个: con = new SqlConnection(cs); con.Open(); DateTime current = DateTime.Now; current = Convert.ToDat

我在数据库中使用此代码我的日期具有
datetime
datatype,但当我通过表单保存数据时,显示错误:

将varchar数据类型转换为datetime数据类型导致值超出范围

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

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

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

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字符串时,需要附加日期字符串,而不是日期时间变量。因此,除非您有其他原因认为当前变量是日期,否则我会将其设置为字符串

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;

检查
Date
字段是否确实是错误建议的
Date/Time
数据类型或
varchar
。使用Szymon建议的参数
string current = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"));