在向数据库插入数据时将空字符串设置为null

4

我一直没有找到解决这个问题的正确方法,虽然它很简单但我已经忘记了如何做。我有一个表单,其中有一个文本字段是用户不需要填写的。我想要将NULL插入到数据库中,而不是当前正在执行的0。虽然我不确定我缺少什么,但文本框的名称为taxRateTxt,而我目前的方法对我来说不起作用:

try
{
    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
    {
        cn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cn;

        cmd.Parameters.Add(new SqlParameter("@FIPSCountyCode", countyCodeTxt.Text));
        cmd.Parameters.Add(new SqlParameter("@StateCode", stateCodeList.SelectedValue));
        cmd.Parameters.Add(new SqlParameter("@CountyName", countyNameTxt.Text));

        string taxStr = taxRateTxt.Text;
        //test for an empty string and set it to db null
        if (taxStr == String.Empty)
        {
            taxStr = DBNull.Value;

        }

        cmd.Parameters.Add(new SqlParameter("@TaxRate", taxStr));

        if (AddBtn.Visible == true)

            cmd.CommandText = addQuery;

        if (EditBtn.Visible == true)
        {
            cmd.CommandText = editQuery;
        }

        cmd.ExecuteNonQuery();
        cn.Close();
    }

我这里缺少什么?

你为这个列设定了默认值吗? - abhi
你的语句 taxStr = DBNull.Value; 应该会导致编译时错误。 - Habib
如果需要插入null值,只需从您的插入SQL脚本中省略该字段(如果该字段没有默认值)。您能否将您的插入脚本添加到帖子中? - Maryam Arshi
2个回答

23

删除这段代码

string taxStr = taxRateTxt.Text;
//test for an empty string and set it to db null
if (taxStr == String.Empty)
{
    taxStr = DBNull.Value;

}

并更改此内容

cmd.Parameters.Add(new SqlParameter("@TaxRate", taxStr));

到这里

cmd.Parameters.Add(new SqlParameter("@TaxRate", string.IsNullOrEmpty(taxRateTxt.Text) ? (object)DBNull.Value : taxRateTxt.Text));

1
喜欢将 DBNull.Value 强制转换为 object 的技巧。省了很多时间 -) - Evan L

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接