![](/img/trans.png)
[英]C# & SQL Server : how to Insert DBNull.Value in command parameter if string value is empty?
[英]DBNull.Value being saved as Empty String
这是我下面的方法,此方法附加到附加到ASPXGridview的数据源。 我的问题是,即使将“ N / A”作为“语言”传递给此SP,有时在数据库中也会将其保存为空字符串。 这不会一直发生...
关于为什么将其保存为空字符串的任何想法?
public static void MaintainConfig(int ID, int ConfigVersionID, string Key, string Value, string Description, string Language)
{
SqlConnection conn = xxxServicesConnection();
SqlCommand cmd = new SqlCommand("MaintainConfig", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@configID", ID);
cmd.Parameters.AddWithValue("@configVersionID", ConfigVersionID);
cmd.Parameters.AddWithValue("@key", Key);
cmd.Parameters.AddWithValue("@value", Value);
cmd.Parameters.AddWithValue("@desc", Description);
if (Language == "N/A") //if the user wants to remove the language
{
cmd.Parameters.AddWithValue("@lang", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("@lang", Language);
}
conn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException sqlEx)
{
if (sqlEx.Number == 50000)
{
throw sqlEx;
}
else
{
throw new Exception("Database error occured");
}
}
catch (Exception ex)
{
throw new Exception("Database error occured");
}
finally
{
conn.Close();
}
}
Language
可能首先是空字符串。
将if (Language == null)
更改为if (string.IsNullOrEmpty(Language))
如果要排除空格,可以使用string.IsNullOrWhitespace()
。
步骤1:使用String.IsNullOrEmpty()
函数代替NULL
进行比较。
替换为:
else if (Language == null)
{
cmd.Parameters.AddWithValue("@lang", DBNull.Value);
}
随着以下:
else if (String.IsNullOrEmpty(Language.Trim()))
{
cmd.Parameters.AddWithValue("@lang", DBNull.Value);
}
步骤2:在比较之前修剪值:
替换为:
if (Language == "N/A") //if the user wants to remove the language
{
cmd.Parameters.AddWithValue("@lang", DBNull.Value);
}
随着以下:
if (Language.Trim().Equals("N/A")) //if the user wants to remove the language
{
cmd.Parameters.AddWithValue("@lang", DBNull.Value);
}
最终解决方案:如果字符串包含NULL
则Trim()
引发Exception,因此在对值进行修整之前检查NULL
。
if (String.IsNullOrEmpty(Language))
{
cmd.Parameters.AddWithValue("@lang", DBNull.Value);
}
else if(Language.Trim().Equals("N/A"))
{
cmd.Parameters.AddWithValue("@lang", DBNull.Value);
}
else if(Language.Trim().Equals(""))
{
cmd.Parameters.AddWithValue("@lang", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("@lang", Language);
}
当Language
为空字符串时,将照原样保存。
换线
if (Language == null)
至
if (String.IsNullOrEmpty(Language))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.