设置数据库值设置为null与一个SqlCommand +参数 [英] Set a database value to null with a SqlCommand + parameters

查看:291
本文介绍了设置数据库值设置为null与一个SqlCommand +参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是previously今天学会了如何在这个答案坐落在.NET中的SQL查询参数(<一href="http://stackoverflow.com/questions/169359/improving-$c$c-readability-for-sql-commands#169369">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;
    }

这篇关于设置数据库值设置为null与一个SqlCommand +参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆