如何清晰快速地使用 DBNull.Value 参数化空字符串

发布于 2024-08-28 04:15:30 字数 1164 浏览 8 评论 0原文

我厌倦了编写以下代码:

/* Commenting out irrelevant parts
public string MiddleName;
public void Save(){
    SqlCommand = new SqlCommand();
    // blah blah...boring INSERT statement with params etc go here. */
    if(MiddleName==null){
        myCmd.Parameters.Add("@MiddleName", DBNull.Value);
    }
    else{
        myCmd.Parameters.Add("@MiddleName", MiddleName);
    }
    /*
    // more boring code to save to DB.
}*/

所以,我写了这样的:

public static object DBNullValueorStringIfNotNull(string value)
{
    object o;
    if (value == null)
    {
        o = DBNull.Value;
    }
    else
    {
        o = value;
    }
    return o;
}

// which would be called like:
myCmd.Parameters.Add("@MiddleName", DBNullValueorStringIfNotNull(MiddleName));

如果这是执行此操作的好方法,那么您建议使用什么作为方法名称? DBNullValueorStringIfNotNull 有点冗长和令人困惑。

我也对完全缓解这个问题的方法持开放态度。我很想这样做:

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? DBNull.Value : MiddleName);

但这行不通,因为“Operator '??'不能应用于“string”和“System.DBNull”类型的操作数”。

如果需要的话,我可以使用 C# 3.5 和 SQL Server 2005。

I got tired of writing the following code:

/* Commenting out irrelevant parts
public string MiddleName;
public void Save(){
    SqlCommand = new SqlCommand();
    // blah blah...boring INSERT statement with params etc go here. */
    if(MiddleName==null){
        myCmd.Parameters.Add("@MiddleName", DBNull.Value);
    }
    else{
        myCmd.Parameters.Add("@MiddleName", MiddleName);
    }
    /*
    // more boring code to save to DB.
}*/

So, I wrote this:

public static object DBNullValueorStringIfNotNull(string value)
{
    object o;
    if (value == null)
    {
        o = DBNull.Value;
    }
    else
    {
        o = value;
    }
    return o;
}

// which would be called like:
myCmd.Parameters.Add("@MiddleName", DBNullValueorStringIfNotNull(MiddleName));

If this is a good way to go about doing this then what would you suggest as the method name? DBNullValueorStringIfNotNull is a bit verbose and confusing.

I'm also open to ways to alleviate this problem entirely. I'd LOVE to do this:

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? DBNull.Value : MiddleName);

but that won't work because the "Operator '??' cannot be applied to operands of type 'string and 'System.DBNull'".

I've got C# 3.5 and SQL Server 2005 at my disposal if it matters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

骄傲 2024-09-04 04:15:30

将您的任何一个值转换为 object 并且它将编译。

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? (object)DBNull.Value : MiddleName);

Cast either of your values to object and it will compile.

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? (object)DBNull.Value : MiddleName);
一世旳自豪 2024-09-04 04:15:30

您可以使用 SqlString.Null 而不是 DBNull.Value 来避免显式转换为 object

MiddleName ?? SqlString.Null

int、datetime 等都有相应的类型四。这是一个带有更多示例的代码片段:

 cmd.Parameters.AddWithValue("@StartDate", StartDate ?? SqlDateTime.Null);
 cmd.Parameters.AddWithValue("@EndDate", EndDate ?? SqlDateTime.Null);
 cmd.Parameters.AddWithValue("@Month", Month ?? SqlInt16.Null);
 cmd.Parameters.AddWithValue("@FormatID", FormatID ?? SqlInt32.Null);
 cmd.Parameters.AddWithValue("@Email", Email ?? SqlString.Null);
 cmd.Parameters.AddWithValue("@ZIP", ZIP ?? SqlBoolean.Null);

You can avoid the explicit cast to object using SqlString.Null instead of DBNull.Value:

MiddleName ?? SqlString.Null

There are corresponding types for int, datetime, and so forth. Here's a code snippet with a couple more examples:

 cmd.Parameters.AddWithValue("@StartDate", StartDate ?? SqlDateTime.Null);
 cmd.Parameters.AddWithValue("@EndDate", EndDate ?? SqlDateTime.Null);
 cmd.Parameters.AddWithValue("@Month", Month ?? SqlInt16.Null);
 cmd.Parameters.AddWithValue("@FormatID", FormatID ?? SqlInt32.Null);
 cmd.Parameters.AddWithValue("@Email", Email ?? SqlString.Null);
 cmd.Parameters.AddWithValue("@ZIP", ZIP ?? SqlBoolean.Null);
树深时见影 2024-09-04 04:15:30

就我个人而言,这就是我对扩展方法所做的事情(确保它进入静态类)

public static object GetStringOrDBNull(this string obj)
{
    return string.IsNullOrEmpty(obj) ? DBNull.Value : (object) obj
}

然后你就可以了

myCmd.Parameters.Add("@MiddleName", MiddleName.GetStringOrDBNull());

Personally this is what I would do with an extension method (make sure this goes into a static class)

public static object GetStringOrDBNull(this string obj)
{
    return string.IsNullOrEmpty(obj) ? DBNull.Value : (object) obj
}

Then you'd have

myCmd.Parameters.Add("@MiddleName", MiddleName.GetStringOrDBNull());
会发光的星星闪亮亮i 2024-09-04 04:15:30
myCmd.Parameters.Add("@MiddleName", MiddleName ?? (object)DBNull.Value);
myCmd.Parameters.Add("@MiddleName", MiddleName ?? (object)DBNull.Value);
埖埖迣鎅 2024-09-04 04:15:30

@David 感谢您的建议。下面的方法效果很好!

MiddleName ?? (object)DBNull.Value

@David Thanks for your suggestion. The following method works great!

MiddleName ?? (object)DBNull.Value
℡寂寞咖啡 2024-09-04 04:15:30

是的,我们都喜欢这样做 myCmd.Parameters.Add("@MiddleName", MiddleName ?? DBNull.Value);。或者更好的是,让奇怪的 SqlClient 层了解添加参数时 CLR null 应该映射到 DBNull.Value。不幸的是,.Net 类型系统关闭了第一个选项,而 SqlClient 的实现则关闭了第二个选项。

我会使用众所周知的函数名称,例如 CoalesceIsNull。任何数据库开发人员只要从名字上就能立刻认出他们在做什么。

Yeap, we'd all love to do myCmd.Parameters.Add("@MiddleName", MiddleName ?? DBNull.Value);. Or better still, have the freakin' SqlClient layer understand that CLR null should be mapped to DBNull.Value when adding a parameter. Unfortunately the .Net type system closes the first alternative, and the implementation of SqlClient closes the second.

I'd go with a well known function name, like Coalesce or IsNull. Any DB developer will recognize what they do in an instant, from the name alone.

不及他 2024-09-04 04:15:30

我宁愿给你两个完全不同的建议:

  1. 使用 ORM。有很多非侵入式 ORM 工具。

  2. 编写您自己的包装器来构建命令,并具有更清晰的界面。像这样的东西:

    公共类 MyCommandRunner {
      私有 SqlCommand cmd;
    
      公共MyCommandRunner(字符串命令文本){
        cmd = new SqlCommand(commandText);
      }
    
      公共无效AddParameter(字符串名称,字符串值){
        如果(值==空)
         cmd.Parameters.Add(名称, DBNull.Value);
        别的
          cmd.Parameters.Add(名称,值);
      }
    
      // ... 更多 AddParameter 重载
    }
    

如果将 AddParameter 方法重命名为 Add,则可以以非常灵活的方式使用它:

var cmd = new MyCommand("INSERT ...")
  {
    { "@Param1", null },
    { "@Param2", p2 }
  };

I'd rather give you two totally different suggestions:

  1. Use an ORM. There are plenty of non-intrusive ORM tools.

  2. Write your own wrapper for building commands, with a cleaner interface. Something like:

    public class MyCommandRunner {
      private SqlCommand cmd;
    
      public MyCommandRunner(string commandText) {
        cmd = new SqlCommand(commandText);
      }
    
      public void AddParameter(string name, string value) {
        if (value == null)
         cmd.Parameters.Add(name, DBNull.Value);
        else
          cmd.Parameters.Add(name, value);
      }
    
      // ... more AddParameter overloads
    }
    

If you rename your AddParameter methods to just Add, you can use it in a very slick way:

var cmd = new MyCommand("INSERT ...")
  {
    { "@Param1", null },
    { "@Param2", p2 }
  };
唠甜嗑 2024-09-04 04:15:30

我建议使用可为空的属性而不是公共字段和“AddParameter”方法(不知道这段代码是否经过优化或正确,就在我的脑海中):


private string m_MiddleName;

public string MiddleName
{
  get { return m_MiddleName; }
  set { m_MiddleName = value; }
}

.
.
.

public static void AddParameter(SQLCommand cmd, string parameterName, SQLDataType dataType, object value)
{
  SQLParameter param = cmd.Parameters.Add(parameterName, dataType);

  if (value is string) { // include other non-nullable datatypes
    if (value == null) {
      param.value = DBNull.Value;
    } else {
      param.value = value;
    }
  } else { 

    // nullable data types
    // UPDATE: HasValue is for nullable, not object type
    if (value.HasValue) // {{{=====================================================
    {
          param.value = value;
    } else 
    {
          param.value = DBNull.Value;
    }
  }
}

.
.
.
AddParameter(cmd, "@MiddleName", SqlDbType.VarChar, MiddleName);

I would suggest using nullable properties instead of public fields and an 'AddParameter' method (don't know if this code is optimized or correct, just off the top of my head):


private string m_MiddleName;

public string MiddleName
{
  get { return m_MiddleName; }
  set { m_MiddleName = value; }
}

.
.
.

public static void AddParameter(SQLCommand cmd, string parameterName, SQLDataType dataType, object value)
{
  SQLParameter param = cmd.Parameters.Add(parameterName, dataType);

  if (value is string) { // include other non-nullable datatypes
    if (value == null) {
      param.value = DBNull.Value;
    } else {
      param.value = value;
    }
  } else { 

    // nullable data types
    // UPDATE: HasValue is for nullable, not object type
    if (value.HasValue) // {{{=====================================================
    {
          param.value = value;
    } else 
    {
          param.value = DBNull.Value;
    }
  }
}

.
.
.
AddParameter(cmd, "@MiddleName", SqlDbType.VarChar, MiddleName);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文