在操作数据库时,我们需要注意一点,就是in查询的参数不能超过1000个,否则会报错,所以我们在进行in查询的时候需要对参数数量进行控制:
用于分解数组的扩展方法:
/// <summary> /// 根据数量对数组进行分组(in查询不能超过1000个条目) /// </summary> /// <param name="list"></param> /// <param name="size">数量</param> private List<List<long>> GroupListBySize(List<long> list,int size) { List<List<long>> listArr = new List<List<long>>(); int arrSize = list.Count() % size == 0 ? list.Count() / size : list.Count() / size + 1; for (int i = 0; i < arrSize; i++) { List<long> sub = new List<long>(); for (int j = i * size; j <= size * (i + 1) - 1; j++) { if (j <= list.Count() - 1) { sub.Add(list[j]); } } listArr.Add(sub); } return listArr; }
如:数组长度为2500,size(按照多少数量进行分割),这里我们传1000,则会被分解为三个数组,长度分别为,1000,1000,500;
业务层的方法接口:
/// <summary> /// 根据id批量修改状态 /// </summary> /// <returns></returns> public bool ButchChangeState(List<long> ids, int state) { if (ids.Count > 0) { if (ids.Count()>1000) { var lists = GroupListBySize(ids,1000); foreach (var list in lists) { dal.ButchChangeState(list,state); } } else { dal.ButchChangeState(ids, state); } return true; } else { return false; } }
数据库交互:
/// <summary> /// 修改状态////0:已执行,1:执行中,2:执行失败,3:待下发 /// </summary> /// <param name="ids"></param> /// <param name="state"></param> /// <returns></returns> public bool ButchChangeState(List<long> ids, int state) { if (ids.Count > 0) { string idStr = string.Join(",", ids); //List数组的每个元素加上引号,如("12","32","5456","876455") string idString = string.Format("'{0}'", idStr.Replace(",", "','")); string sql = $" update COMMAND_ACCESSLOG set WORKSTATE = {state},STRING1=:DOWNSENDTIME where COMMANDID in ( {idString} )"; OracleParameter[] parameters = { new OracleParameter(":DOWNSENDTIME",OracleDbType.Varchar2,1024) }; parameters[0].Value = DateTime.Now.ToString(); var row = DbHelperOra.ExecuteSql(sql,parameters); return row > 0 ? true : false; } else { return false; } }