2023年6月21日发(作者:)

C#SQLServer往数据库插⼊更新时候关于NUll空值的处理前⼏天遇到⼀个问题,找了好久才找到解决办法。不过也很开⼼,终于解决了。问题:前端当我数据为空的时候不赋值,传到后台也为空的时候(注意:是Null不是""),SqlCommand对传送的参数中如果字段的值是NULL具然不进⾏更新操作。插⼊、更新操作都不进⾏,现在咱们拿插⼊为例(更新同理)。例:public bool Insert(SysNotify notify){ SqlParameter[] parameters = new SqlParameter[] {   new SqlParameter("@Title", ),   new SqlParameter("@NotifyType", Type),   new SqlParameter("@NotifyContent", Content) }; string sqlStr = @" INSERT INTO SysNotify(Title, NotifyType, NotifyContent)

VALUES(@Title, @NotifyType, @NotifyContent) "; return eNonQuery(, sqlStr, parameters);}这⾥就是当为Null时,就会报错,所以要对这个字段处理⼀下。解决办法:我使⽤扩展⽅法封装了⼀个静态⽅法:#region 判断数据为空时,获取其DBNull的值 徐悦 2019年2⽉23⽇17:16:35///

/// 判断数据为空时,获取其DBNull的值/// /// /// public static object GetDBNull(this object value){ if (value == null)  { return ; } return value;}#endregion然后按照下⾯这种形式调⽤就可以处理数据为空时的处理public bool Insert(SysNotify notify){ SqlParameter[] parameters = new SqlParameter[] {   new SqlParameter("@Title", ull()),   new SqlParameter("@NotifyType", Type),   new SqlParameter("@NotifyContent", ull()) }; string sqlStr = @" INSERT INTO SysNotify(Title, NotifyType, NotifyContent)

VALUES(@Title, @NotifyType, @NotifyContent) "; return eNonQuery(, sqlStr, parameters);}按照标红处⽅式使⽤就可以解决当数据为空时,SqlCommond执⾏不成功的问题。bingo(o゜▽゜)o☆[BINGO!]

2023年6月21日发(作者:)

C#SQLServer往数据库插⼊更新时候关于NUll空值的处理前⼏天遇到⼀个问题,找了好久才找到解决办法。不过也很开⼼,终于解决了。问题:前端当我数据为空的时候不赋值,传到后台也为空的时候(注意:是Null不是""),SqlCommand对传送的参数中如果字段的值是NULL具然不进⾏更新操作。插⼊、更新操作都不进⾏,现在咱们拿插⼊为例(更新同理)。例:public bool Insert(SysNotify notify){ SqlParameter[] parameters = new SqlParameter[] {   new SqlParameter("@Title", ),   new SqlParameter("@NotifyType", Type),   new SqlParameter("@NotifyContent", Content) }; string sqlStr = @" INSERT INTO SysNotify(Title, NotifyType, NotifyContent)

VALUES(@Title, @NotifyType, @NotifyContent) "; return eNonQuery(, sqlStr, parameters);}这⾥就是当为Null时,就会报错,所以要对这个字段处理⼀下。解决办法:我使⽤扩展⽅法封装了⼀个静态⽅法:#region 判断数据为空时,获取其DBNull的值 徐悦 2019年2⽉23⽇17:16:35///

/// 判断数据为空时,获取其DBNull的值/// /// /// public static object GetDBNull(this object value){ if (value == null)  { return ; } return value;}#endregion然后按照下⾯这种形式调⽤就可以处理数据为空时的处理public bool Insert(SysNotify notify){ SqlParameter[] parameters = new SqlParameter[] {   new SqlParameter("@Title", ull()),   new SqlParameter("@NotifyType", Type),   new SqlParameter("@NotifyContent", ull()) }; string sqlStr = @" INSERT INTO SysNotify(Title, NotifyType, NotifyContent)

VALUES(@Title, @NotifyType, @NotifyContent) "; return eNonQuery(, sqlStr, parameters);}按照标红处⽅式使⽤就可以解决当数据为空时,SqlCommond执⾏不成功的问题。bingo(o゜▽゜)o☆[BINGO!]