在插入数据库时,将空字符串设置为空。

问题描述 投票:3回答:3

对于这个问题,我一直没有找到合适的解决方案,我知道这个问题很简单,但是我已经忘记怎么做了。我有一个表单,其中有一个文本字段是用户不需要填写的。我想把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();
    }

我错过了什么?

c# .net string sql-insert dbnull
3个回答
22
投票

删除这段代码

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

4
投票

递进 Convert.DBNull (或 DBNull.Value)就可以了。

http:/msdn.microsoft.comen-uslibrarysystem.convert.dbnull(v=vs.110).aspx。

当然,你必须先检查字符串值,然后再将其传递进来。

© www.soinside.com 2019 - 2024. All rights reserved.