c# - 允许将空日期时间输入数据库吗?

标签 c# sql sql-server datetime

我有两个日历日期选择控件,它们不是完成表单所必需的。但是,每当我尝试在不从日历控件中选择内容的情况下提交表单时,我总是收到此异常错误:

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/

相关文章:

javascript - C# 等效于从现有数组的 .buffer 创建的 javascript TypedArray?

c# - 我应该使用 Html.CheckBox 还是 Html.CheckBoxFor?

mysql - FlashChat 安装问题! SQL语法错误?

sql - 如何搜索整个单词是否存在于 Postgres 的字符串中

sql-server - SQL Server : set a variable in CASE statement

c# - KINECT:如何使用 Kinect 识别用户何时向上或向下行走?

c# - 蛮力- c#

php - 数据库更新错误数据

sql-server - 跳过行: Export data from SSIS into excel file

sql-server - Websphere 中 SQL Server 的 SSL 连接错误