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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 23:45:54  来源:igfitidea点击:

Set a database value to null with a SqlCommand + parameters

.netsql

提问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

you want DBNull.Value.

你想要DBNull.Value。

In my shared DAL code, I use a helper method that just does:

在我共享的 DAL 代码中,我使用了一个辅助方法,它只执行以下操作:

    foreach (IDataParameter param in cmd.Parameters)
    {
        if (param.Value == null) param.Value = DBNull.Value;
    }

回答by Emile Cormier

I use a SqlParameterCollectionextension method that allows me to add a parameter with a nullable value. It takes care of converting nullto DBNull. (Sorry, I'm not fluent in VB.)

我使用了一个SqlParameterCollection扩展方法,它允许我添加一个具有可为空值的参数。它负责转换nullDBNull. (对不起,我不精通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.