SQL 使用 SqlCommand + 参数将数据库值设置为 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/170186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set a database value to null with a SqlCommand + parameters
提问by RodgerB
I was previously taught today how to set parameters in a SQL query in .NET in this answer (click).
今天我之前在这个答案中学习了如何在 .NET 中的 SQL 查询中设置参数(单击)。
Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter.
使用带值的参数很好,但是当我尝试将数据库中的字段设置为 null 时,我没有成功。该方法认为我没有设置有效参数或未指定参数。
e.g.
例如
Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn)
If actLimit.ToLower() = "unlimited" Then
' It's not nulling :(
dc.Parameters.Add(New SqlParameter("Limit", Nothing))
Else
dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit)))
End If
Is there something I'm missing? Am I doing it wrong?
有什么我想念的吗?我做错了吗?
回答by Marc Gravell
回答by Emile Cormier
I use a SqlParameterCollection
extension method that allows me to add a parameter with a nullable value. It takes care of converting null
to DBNull
. (Sorry, I'm not fluent in VB.)
我使用了一个SqlParameterCollection
扩展方法,它允许我添加一个具有可为空值的参数。它负责转换null
为DBNull
. (对不起,我不精通VB。)
public static class ExtensionMethods
{
public static SqlParameter AddWithNullable<T>(this SqlParameterCollection parms,
string parameterName, T? nullable) where T : struct
{
if (nullable.HasValue)
return parms.AddWithValue(parameterName, nullable.Value);
else
return parms.AddWithValue(parameterName, DBNull.Value);
}
}
Usage:
用法:
string? optionalName = "Bozo";
cmd.Parameters.AddWithNullable("@Name", optionalName);
回答by Sklivvz
Try setting it to DbNull.Value
.
尝试将其设置为DbNull.Value
.