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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM