我有两个日历日期选择控件,它们不是完成表单所必需的。但是,每当我尝试在不从日历控件中选择内容的情况下提交表单时,我总是收到此异常错误:
Exception: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
在数据库中,我的 SQL 表已设置为允许两个日期时间字段为空值。
有没有办法在不导致错误的情况下允许这两个字段为空或空白条目?
这是将表单信息保存到数据库的代码(我将其缩减为仅包含 2 个日期时间字段):
private void SaveCustomerInfo(int CustID)
{
int currentUserID = AbleContext.Current.UserId;
string addQuery = "INSERT INTO Customers (TaxExemptDate, AuthDate) VALUES(@TaxExemptDate, @AuthDate)";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand(addQuery, cn);
cmd.Connection = cn;
cmd.Parameters.Add(new SqlParameter("@TaxExemptDate", TaxExemptDate.SelectedStartDate));
cmd.Parameters.Add(new SqlParameter("@AuthDate", AuthDate.SelectedStartDate));
_CustomerID = AlwaysConvert.ToInt(Request.QueryString["CustomerID"]);
int.TryParse(Request.QueryString["CustomerID"], out _CustomerID);
if (_CustomerID == 0)
{
cmd.CommandText = addQuery;
}
if (_CustomerID !=0)
{
cmd.Parameters.Add(new SqlParameter("@CustomerID", CustID));
cmd.CommandText = editQuery;
}
cmd.ExecuteNonQuery();
cn.Close();
}
}
catch (Exception exception)
{
Logger.Warn("Admin\\People\\Customers\\EdutCustomer.aspx - SaveCustomerInfo", exception);
}
}
最佳答案
您不传递 null,而是通过 SqlParameter 传递 DBNull.Value
cmd.Parameters.Add(new SqlParameter("@TaxExemptDate", TaxExemptDate.SelectedStartDate == null ? (Object)DBNull.Value : TaxExemptDate.SelectedStartDate));
或
cmd.Parameters.Add(new SqlParameter("@TaxExemptDate", TaxExemptDate.SelectedStartDate == DateTime.MinValue ? (Object)DBNull.Value : TaxExemptDate.SelectedStartDate));
关于c# - 允许将空日期时间输入数据库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25207803/