English 中文(简体)
.Net从变量值插入NULL值到SQL Server数据库
原标题:
  • 时间:2009-03-06 15:26:30
  •  标签:

有类似的问题,但回答并不是我要找的。如果引用为NULL或尚未分配值,我想将NULL值插入SQL Server数据库。目前我正在测试null并且看起来......(无法翻译完整,因为上下文不够清晰)

String testString = null;

if (testString == null)
{
    command.Parameters.AddParameter(new SqlParameter("@column", DBNull.Value);
}
else
{
    command.Parameters.AddParameter(new SqlParameter("@column", testString);
}

这对我来说看起来感觉非常笨拙。我有很多要插入到数据库中的值,像上面那样测试它们很冗长。.Net没有以某种方式处理这个吗?我以为如果我使用字符串而不是String可能会有用,但似乎也不起作用。我在四处寻找发现了一些关于使用Nullable类型的文章。

System.Nullable<T> variable

这似乎对原始类型、int?、char?double?和bool?都有效。所以这对那些可能有效,但是字符串呢?我有遗漏什么吗?我应该使用哪种类型来代替原始值和字符串值,以便在插入它们之前不需要重复测试值。

EDIT: Before I get too many answers about ternary operators. I like them but not in this context. It doesn t make sense for me to need to test that value and have all that extra logic, when that sort of thing could have been inplemented lower down in the .Net framework and if I knew what types to give then it would get it for free.

Edit: Okay, so guys help me formulate my plan of attack. I will use the Nullable for my primitives (int?, double? etc) and for my Strings I will use the String but the ?? test. This keeps things less verbose. Is there anything that I am missing here, like maybe losing some semantics?

最佳回答

比三元运算符更好的是双问号(??)运算符。取第一个非空值。因此:

string x = null;
command.Parameters.AddParameter(
     new SqlParameter("@column", (object)x ?? DBNull.Value);

我会把一个值为DBNull.Value的parm给你,但是

string x = "A String";
command.Parameters.AddParameter(
     new SqlParameter("@column", (object)x ?? DBNull.Value);

会给你一个带有值“字符串”的parm。

问题回答

Nullable 对于基本类型非常好用。我需要测试字符串的行为,但至少可以定义一个字符串的扩展方法来清理你的代码。

你可以使用“??”运算符操作字符串:

command.Parameters.AddParameter(new SqlParameter("@column", myNull ?? (object)DBNull.Value); command.Parameters.AddParameter(new SqlParameter("@column", myNull ?? (object)DBNull.Value);

如果第一项不为空,则返回第一项,否则返回第二项。

Edit

将以上代码进行修复,需要将DBNull.Value强制转换为一个对象使其能够编译通过。

也许三元操作符是你觉得有用的东西。

我有时候会这样做:

command.Parameters.Add ("@column", SqlDbType.VarChar).Value = DBNull.Value;

if( String.IsNullOrEmpty (theString) == false )
{
    command.Parameters["@column"].Value = theString;
}

我同意这种SqlParameter.Value必须设置为DbNull.Value有些笨拙和不幸。但是没有其他办法,所以你必须使用测试空值来处理。

Nullable<T>不能应用于String,因为它是引用类型而不是值类型。

例子:

if (txtDisplayName.Text != "")
{
    insert into table (id,display_name) values ( " + txtID.Text + " , " + txtDisplayName.Text + " );
}
else
{
    insert into table (id) values ( " + txtID.Text + " );
}

这将插入null





相关问题
热门标签