sqldatetime溢出exceptionc#.NET
string con = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString; SqlConnection cn = new SqlConnection(con); string insert_jobseeker = "INSERT INTO JobSeeker_Registration(Password,HintQuestion,Answer,Date)" + " values (@Password,@HintQuestion,@Answer,@Date)"; SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = insert_jobseeker; cmd.Parameters.Add(new SqlParameter("@Password", SqlDbType.VarChar, 50)); cmd.Parameters["@Password"].Value = txtPassword.Text; cmd.Parameters.Add(new SqlParameter("@HintQuestion", SqlDbType.VarChar, 50)); cmd.Parameters["@HintQuestion"].Value = ddlQuestion.Text; cmd.Parameters.Add(new SqlParameter("@Answer", SqlDbType.VarChar, 50)); cmd.Parameters["@Answer"].Value = txtAnswer.Text; **cmd.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime)); cmd.Parameters["@Date"].Value = System.DateTime.Now**
我收到了错误
“SqlDateTime溢出。必须在1/1/1753 12:00:00 AM和12/31/9999 11:59:59 PM之间。”
这是什么解决方案?
尝试将SQL Server端的@Date
类型更改为DATETIME2(7)
然后在您的代码中使用此行代替:
cmd.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime2));
您的代码看起来没问题如图所示,但由于本地化问题或您的Region / Time设置有问题,转换可能会发生转换,因此请查看是否有效。
如果您使用的是SQL Server 2008
及更高版本,则可以执行以下操作:
第1步:将您的@Date
数据类型从DATETIME
更改为DATETIME2(7)
第2步:在您的代码隐藏中,使用:
SqlDbType.DateTime2
“Date”是关键字,不要将其用作列名。 如果必须,请在插入语句中将其括在[]中:[Date]但最好将其更改为其他内容,例如“RegistrationDate”。