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!]

  • 相关阅读:
    南北朝
    霍去病
    晋 司马
    唐代 诗人
    Getting Started with Google Tango(Google Tango开始教程)
    第二届普适计算和信号处理及应用国际会议论文2016年 The 2nd Conference on Pervasive Computing, Signal Processing and Applications(PCSPA, 2016)
    TurtleBot教程
    ROS教程
    《SLAM for Dummies》中文版《SLAM初学者教程》
    Sensor fusion(传感器融合)
  • 原文地址:https://www.cnblogs.com/pukua/p/10509401.html
Copyright © 2011-2022 走看看