使用SqlCommand +参数将数据库值设置为null

Rod*_*erB 30 .net sql

我今天教过如何在这个答案中单击 .NET中的SQL查询中的参数(单击).

使用带有值的参数很好,但是当我尝试将数据库中的字段设置为null时,我不成功.该方法认为我没有设置有效参数或没有指定参数.

例如

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
Run Code Online (Sandbox Code Playgroud)

有什么我想念的吗?我做错了吗?

Mar*_*ell 77

你想要DBNull .Value.

在我的共享DAL代码中,我使用了一个辅助方法:

    foreach (IDataParameter param in cmd.Parameters)
    {
        if (param.Value == null) param.Value = DBNull.Value;
    }
Run Code Online (Sandbox Code Playgroud)


Emi*_*ier 8

我使用一个SqlParameterCollection扩展方法,允许我添加一个可以为null的值的参数.它负责转换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);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

string? optionalName = "Bozo";
cmd.Parameters.AddWithNullable("@Name", optionalName);
Run Code Online (Sandbox Code Playgroud)