原创地址:http://blog.csdn.net/zdb330906531
我在批量更新十万级别的数据时,遍历表格出现内存溢出,于是琢磨能不能把要更新的数据,直接保存到泛型里面,然后遍历泛型来执行保存方法。
经过测试发现执行效率确实有质的飞跃,所以在此分享,希望对遇到同样问题的你有所帮助。
批量更新类
/// <summary>
/// 批量更新类
/// </summary>
public class BatchUpdate
{
/// <summary>
/// 列名称
/// </summary>
public string columnName { get; set; }
/// <summary>
/// 标识Id
/// </summary>
public List<string> txID { get; set; }
/// <summary>
/// 错误或警告
/// </summary>
public string error { get; set; }
/// <summary>
/// 无区别错误(指当前列名称下的所有旧值都要改的情况)
/// <para>比如:代码错误,所有的代码都要改</para>
/// <para>默认:false</para>
/// </summary>
public bool difference { get; set; }
/// <summary>
/// 旧值
/// </summary>
public string oldValue { get; set; }
/// <summary>
/// 新值
/// </summary>
public string newValue { get; set; }
/// <summary>
/// 过滤条件
/// </summary>
public string filter { get; set; }
#region 重写比较
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (this.GetType() != obj.GetType())
return false;
return this.columnName.Equals((obj as BatchUpdate).columnName) && this.error.Equals((obj as BatchUpdate).error);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
}
批量更新数据
/// <summary>
/// 用于批量更新数据
/// </summary>
List<BatchUpdate> updateLite = new List<BatchUpdate>();
//存放批量修改信息
BatchUpdate update = new BatchUpdate();
update.columnName = "列名";
update.difference = true;
update.error = "错误信息";
update.oldValue = "旧值";
update.newValue = "新值";
//处理带条件的值
if (条件判断)
{
update.filter = "条件";
}
List<string>() txidList = new List<string>();
txidList.Add(编号);
update.txID = txidList;
BatchUpdate update2 = updateLite.Find(delegate(BatchUpdate u) {
return u.columnName.Equals(update.columnName) && u.error.Equals(update.error);
});
if (update2 != null)
{
//如果新值与旧值不一致,以新值为准
if (update2.newValue != update.newValue)
{
update.oldValue = update2.oldValue;
updateLite.Remove(update2);
updateLite.Add(update);
}
}
else
{
updateLite.Add(update);
}
保存
//保存
foreach (BatchUpdate updateStr in updateLite)
{
if (updateStr.difference && updateStr.txID == null)
{
cmd.CommandText = string.Format("update 表 set {0}='{1}' where {0}='{2}' {3}", updateStr.columnName, updateStr.newValue,
updateStr.oldValue, updateStr.filter);
cmd.ExecuteNonQuery();
}
else if (updateStr.txID.Count == 1)
{
cmd.CommandText = string.Format("update 小班 set {0}='{1}' where 图形ID={2} {3}", updateStr.columnName, updateStr.newValue,updateStr.txID[0], updateStr.filter);
cmd.ExecuteNonQuery();
}
else
{
cmd.CommandText = string.Format("update 表 set {0}='{1}' where Id in ({2})", updateStr.columnName, updateStr.newValue, string.Join(",", ids.ToArray()));
cmd.ExecuteNonQuery();
}
}