Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

.net - Set a database value to null with a SqlCommand + parameters

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

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you want DBNull.Value.

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;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...