zoukankan      html  css  js  c++  java
  • C#:往数据库插入/更新时候关于NUll空值的处理

    前几天遇到一个问题,找了好久才找到解决办法。不过也很开心,终于解决了。

    问题:前端当我数据为空的时候不赋值,传到后台也为空的时候(注意:是Null不是""),SqlCommand对传送的参数中如果字段的值是NULL具然不进行更新操作。

    插入、更新操作都不进行,现在咱们拿插入为例(更新同理)。

    例:

    public bool Insert(SysNotify notify)
    {
        SqlParameter[] parameters = new SqlParameter[]
        {
          new SqlParameter("@Title", notify.Title),
          new SqlParameter("@NotifyType", notify.NotifyType),
          new SqlParameter("@NotifyContent", notify.NotifyContent)
        };
    
        string sqlStr = @" INSERT INTO SysNotify(Title, NotifyType, NotifyContent) 
                           VALUES(@Title, @NotifyType, @NotifyContent) ";
    
        return DbHelper.ExecuteNonQuery(CommandType.Text, sqlStr, parameters);
    }

    这里就是当notify.Title为Null时,就会报错,所以要对notify.Title这个字段处理一下。

    解决办法:

    我使用扩展方法封装了一个静态方法:

    #region 判断数据为空时,获取其DBNull的值 徐悦 2019年2月23日17:16:35
    /// <summary>
    /// 判断数据为空时,获取其DBNull的值
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static object GetDBNull(this object value)
    {
       if (value == null)
      {
          return DBNull.Value;
       }
       return value;
    }
    #endregion

    然后按照下面这种形式调用就可以处理数据为空时的处理

    public bool Insert(SysNotify notify)
    {
        SqlParameter[] parameters = new SqlParameter[]
        {
          new SqlParameter("@Title", notify.Title.GetDBNull()),
          new SqlParameter("@NotifyType", notify.NotifyType),
          new SqlParameter("@NotifyContent", notify.NotifyContent.GetDBNull())
        };
    
        string sqlStr = @" INSERT INTO SysNotify(Title, NotifyType, NotifyContent) 
                           VALUES(@Title, @NotifyType, @NotifyContent) ";
    
        return DbHelper.ExecuteNonQuery(CommandType.Text, sqlStr, parameters);
    }

    按照标红处方式使用就可以解决当数据为空时,SqlCommond执行不成功的问题。

    bingo(o゜▽゜)o☆[BINGO!]

  • 相关阅读:
    Spring学习笔记02-配置bean(第七周)
    Spring学习笔记01
    构建之法阅读笔记02
    keep running-团队视频分析初步总结
    影视分享App(三)(第六周)
    Delphi 正则表达式语法(6): 贪婪匹配与非贪婪匹配
    Delphi 正则表达式语法(5): 边界
    Delphi 正则表达式语法(4): 常用转义字符与 .
    Delphi 正则表达式语法(3): 匹配范围
    Delphi 正则表达式语法(2): 或者与重复
  • 原文地址:https://www.cnblogs.com/pukua/p/10509401.html
Copyright © 2011-2022 走看看