净插入空值转换成从变量值的SQL Server数据库转换成、数据库、变量值、SQL

2023-09-03 13:09:08 作者:请你别敷衍

也出现了类似的问题,但答案是不是我所期待的。我想插入的NULL的一个值到SQL Server数据库如果参考NULL或一个值还没有被分配。目前,我正在测试的空,它看起来像

There have been similar questions but the answers weren't what I was looking for. I want to insert the a value of NULL into the SQL Server database if the reference is NULL or a value has not yet been assigned. At the moment I am testing for null and it looks like

String testString = null;

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

这看起来和感觉令人难以置信的笨拙的我。我有我插入到数据库并测试它们像上面很详细的相当多的价值。不净不以某种方式处理这个问题。我想,也许,如果我使用的字符串,而不是字符串,但也不会出现工作。环顾四周,我发现它谈论使用可空类型的文章。

This looks and feels incredibly clumsy to me. I have quite a few values that I am inserting into a database and to test them all like the above is very verbose. Does .Net not handle this in some way. I thought maybe if I used string as opposed to String but that also does not appear to work. Looking around I found articles which talk about using Nullable types.

System.Nullable<T> variable

这似乎工作的原语,诠释?字符?双?和布尔?所以这可能对那些东西,但有关字符串?我失去了一些东西在这里。我应该是什么类型的使用为原始值和字符串值,这样我将它们插入前不必反复测试值。

This seems to work for primitives, int?, char? double? and bool?. So that might work for those but what about strings? Am I missing something here. What types should I be using for primitive values and for string values so that I do not have to repeatedly test values before inserting them.

编辑: 之前,我对三元运营商太多的答案。我喜欢他们而不是在这样的背景下。它没有任何意义,我需要测试的值,并将所有额外的逻辑,当这种事情本来可以在.NET Framework inplemented低了下去,如果我知道给那么什么类型的它会得到它免费的。

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.

编辑: 好了,你们帮我制定我的攻击计划。我将使用可空我的原语(INT?翻一番?等等),并为我的琴弦,我将使用String但?测试。这使事情变得更简洁。这有什么,我很想念这里,如可能失去一些语义?

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?

推荐答案

甚至比三元更好的为双问号(?)运算符。采用第一个非空值。所以:

Even better than the ternary is the double-question-mark (??) operator. Takes the first non-null value. So:

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

会给你的的DBNull.Value值的PARM,但

would give you a parm with a value of DBNull.Value, but

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

会给你以一个字符串一个PARM作为值。

Would give you a parm with "A String" as the value.