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