c# – 在插入数据库时??将空字符串设置为null
发布时间:2020-12-15 20:06:32 所属栏目:百科 来源:网络整理
导读:我一直无法为这个问题找到合适的解决方案,我知道这很简单,但我忘记了怎么做.我有一个带有一个textfield字段的表单,用户不需要填写.我想在数据库中插入NULL,而不是它当前正在执行的0.不过,我不确定我错过了什么.文本框名为taxRateTxt,我目前所使用的对我不起
我一直无法为这个问题找到合适的解决方案,我知道这很简单,但我忘记了怎么做.我有一个带有一个textfield字段的表单,用户不需要填写.我想在数据库中插入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(); } 我在这里错过了什么? 解决方法
删除这段代码
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)); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |