设置数据库值设置为null与一个SqlCommand +参数设置为、参数、数据库、null

2023-09-03 11:56:32 作者:聖ジ尐晟

我是previously今天学会了如何在这个答案坐落在.NET中的SQL查询参数(click).

I was previously taught today how to set parameters in a SQL query in .NET in this answer (click).

使用的参数,其值都很好,但是当我试图在数据库中设置一个字段设置为null我是不成功的。无论哪种方法认为我没有设定一个有效的参数或不指定一个参数。

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.

例如。

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?

推荐答案

您想要的DBNull .value的。

you want DBNull.Value.

在我的共享DAL code,我使用一个辅助方法,它只是做:

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

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