生产数据库中,大批数据更新时应分批执行
<div><div><div>实际生产中,可能由于需求的变化需要对数据库中的数据做统一的更新。这时由于项目已经上线好久时间,数据库中的数据也已经很多了。这时的更新操作如果一次执行,可能对数据库造成数据阻塞,给用户的浏览造成问题。比较好的做法是每更新一批数据后,就停顿一定的时间。<div style="page-break-after: always;"><span style="display: none;"><!--more-->& nbsp ;</span></div><div align="left"> public void ProcessRequest(HttpContext context)</div><div align="left"> {</div><div align="left"> context.Response.ContentType = "text/html";</div><div align="left"> </div><div align="left"> Entities db = new Entities();</div><div align="left"> </div><div align="left"> int page = 1;</div><div align="left"> </div><div align="left"> while (true )</div><div align="left"> {</div><div align="left"> int take = page 1000;</div><div align="left"> int skip = (page - 1) 1000;</div><div align="left"> var links = db.XXX.OrderBy(p=>p.ContentID).Take(take).Skip(skip).Select(p => new { p.ContentID, p.DownIDs }).ToList();</div><div align="left"> </div><div align="left"> if (links.Count() == 0)</div><div align="left"> {</div><div align="left"> break;</div><div align="left"> }</div><div align="left"> </div><div align="left"> </div><div align="left"> for (int i = 0; i < links.Count; i++)</div><div align="left"> {</div><div align="left"> string[] downIDs = new string[] { };</div><div align="left"> if (string .IsNullOrEmpty(links[i].DownIDs))</div><div align="left"> {</div><div align="left"> continue;</div><div align="left"> }</div><div align="left"> </div><div align="left"> downIDs = links[i].DownIDs.Split( ',');</div><div align="left"> </div><div align="left"> </div><div align="left"> for (int j = 0; j < downIDs.Length; j++)</div><div align="left"> {</div><div align="left"> int contentId = links[i].ContentID;</div><div align="left"> int downId = Convert .ToInt32(downIDs[j]);</div><div align="left"> var query = db.YYY.FirstOrDefault(p => p.ContentID == contentId && p.DownID == downId);</div><div align="left"> if (query == null )</div><div align="left"> {</div><div align="left"> db.YYY.Add( new Y{ ContentID = contentId, DownID = downId, DateAdded = DateTime .Now });</div><div align="left"> </div><div align="left"> }</div><div align="left"> }</div><div align="left"> </div><div align="left"> }</div><div align="left"> db.SaveChanges();</div><div align="left"> context.Response.Write( "<br>");</div><div align="left"> context.Response.Write(links.Count());</div><div align="left"> context.Response.Flush();</div><div align="left"> page++;</div><div align="left"> System.Threading. Thread.Sleep(100);</div><div align="left"> }</div></div></div></div>