C# 将空字符串转换为Null以将Null值保存到SQL Server数据库中
我刚刚读出了非常好的答案,使用C# 将空字符串转换为Null以将Null值保存到SQL Server数据库中,c#,sql-server,sqlcommand,C#,Sql Server,Sqlcommand,我刚刚读出了非常好的答案,使用 string.IsNullOrWhiteSpace(textbox.tex) ? (object)textbox.text: DBNull.Value; 或使用 cmd.Parameters.AddWithValue("foo", foo == null ? (object)DBNull.Value : (object)foo); 我也尝试过其他人,但对我来说不起作用,因为我不是很精通C语言,但我必须将null保存到我的SQL Server数据库列中
string.IsNullOrWhiteSpace(textbox.tex) ? (object)textbox.text: DBNull.Value;
或使用
cmd.Parameters.AddWithValue("foo",
foo == null ? (object)DBNull.Value : (object)foo);
我也尝试过其他人,但对我来说不起作用,因为我不是很精通C语言,但我必须将null保存到我的SQL Server数据库列中
这是我的代码,我试图保存空值,但它发送空字符串,这不是我的要求
oCourseRegistrationPaypal.UserTheoryTrainingDate4 = Convert.ToString(DBNull.Value);
所以当我写作的时候
oCourseRegistrationPaypal.UserTheoryTrainingDate4 = null;
oCourseRegistrationPaypal.UserTheoryTrainingDate4=Convert.ToString(DBNull.Value);
这给了我一个错误,我的过程需要的参数并没有提供,但我知道我已经为它提供了null
当我写作时
oCourseRegistrationPaypal.UserTheoryTrainingDate4 = null;
oCourseRegistrationPaypal.UserTheoryTrainingDate4=Convert.ToString(DBNull.Value);
它将空字符串保存在我的数据库列中,但我需要一个null
值
当我在存储过程中手动保存null值时,它接受null并保存null,但为什么不接受呢
oCourseRegistrationPaypal.UserTheoryTrainingDate4 = null;
从我的C代码
有更好的方法吗 如果将
DBNull.Value
转换为字符串,它将为您提供一个空字符串
只需存储一个DBNull.Value
cmd.Parameters.AddWithValue("foo",
foo == null ? DBNull.Value : foo);
或者:
cmd.Parameters.AddWithValue("foo",
foo ?? DBNull.Value);
编辑:根据您对问题的编辑,将
foo
替换为ocurseregistrationpaypal.UserTheoryTrainingDate4
。我在上面粘贴的代码将null
替换为DBNull.Value
您看到的AddWithValue()
示例有一个问题:它迫使ADO.Net猜测参数的数据库类型。通常它会猜对,但有时它会猜错
cmd.Parameters.AddWithValue("foo",
foo == null ? DBNull.Value : foo);
好消息是,它对大多数代码的猜测都是正确的,即使它猜测了错误的代码,仍然会起作用。然而,这很少会导致代码崩溃并引发异常。一个更常见的问题是,这将导致数据库需要每行转换,或者中断索引使用。它可以接受在测试中立即返回的查询,并使其在生产中运行几分钟
当与条件运算符检查结合使用时,问题会更严重,因为它迫使您将两侧强制转换为对象
。这将删除ADO.Net在猜测数据库类型时得到的最重要提示。ADO.Net看到的不是字符串、Datetime、Double等,而是“Object”作为.Net类型。这使得猜测错误数据库类型的可能性更大。如果这是用于添加空值的go-to模式,那么整个应用程序的性能将处于次优状态
相反,我喜欢这样做:
//explicit DB type, and don't worry about DBNull just yet
cmd.Parameters.Add("foo", SqlDbType.Int).Value = foo;
cmd.Parameters.Add("bar", SqlDbType.NVarChar, 30).Value = bar;
//if you have more parameters, add them all this way
// after all parameters are added:
foreach(var p in cmd.Parameters.Where(p => p.Value == null))
{
p.Value = DBNull.Value;
}
这里有一个警告:像int和DateTime这样的值类型永远不会匹配该条件,因此我的实际代码必须稍微复杂一点(涉及
Nullable
s)。但希望它能给你一个正确的想法。当我试图保存oCourseRegistrationPaypal.UserTheoryTrainingDate2=DBNull.Value;它给我的错误是无法将dbnull转换为字符串。因为dbnull.Value不是字符串。我不想使用sql参数等保存null,但我只想在oCourseRegistrationPaypal.UserTheoryTrainingDate2中保存null?可能吗?是的,ocurseregistrationpaypal.UserTheoryTrainingDate2=null
。听起来你可能把null
与DBNull
混淆了。后者用于将null指定为SQL/db参数。前者几乎在其他任何地方都用来表示null。oCourseRegistrationPaypal到底是什么?不要将DBNull.Value
转换为object。直接保存。@attila它是我的自定义类型层的对象,我想在这个对象中存储null,然后我将这个对象传递到数据访问层,在那里我已经写下了保存过程。