幾個月沒有更新筆記了,最近遇到一個坑爹的問題,順道記錄一下。。
需求是這樣的:一次性修改上萬條數據庫。
項目是用MVC+linq的。
本來想著用 直接where()
1 | var latentCustomerList = this .FindAll().Where(m => arrId.Contains(m.CustomerID.ToString())).ToList(); |
這樣子執行,意料之中的就是出錯了,出啥錯,自己試了就知道了。哈哈
想來就只有直接操作數據庫了。第一次的想法,直接就是for拼接語句,拼是拼了。
123456 | for ( int i = 0; i < obaList.Count; i++)
{
arrId[i] = obaList[i].CustomerID.ToString();
sbUpdateSqlStr.AppendFormat( "update dbo.Customer set IsValid=1 where CustomerID='{0}' ; " , arrId[i]);
} |
可是執行起來總共花費了7秒。第二次花費4.5秒,第三次5秒。
數據庫都是爭分奪毫秒。這樣拼了一萬多條的語句還真不是辦法。調試進去也許你也會崩潰。。。就想著能不能快,再快。就想到了IN
于是就改成了下面的方法。
123456789101112131415 | for ( int i = 0 ; i < obaList.Count; i++)
{
arrId[i] = obaList[i].CustomerID.ToString();
if (i != 0 && i % 50 == 0 )
{
ids = ids.Remove(ids.Length - 1 );
sbUpdateSqlStr.AppendFormat( "update dbo.Customer set IsValid=1 where CustomerID in({0}) ; " , ids);
ids = "'" + arrId[i] + "'," ;
}
else
{
ids += "'" + arrId[i] + "'," ;
}
} |
看看總共的執行時間吧。。
也只能是這樣的速度了...
說說最后的思想吧,其實就是減少執行語句數量的問題,把原本需要執行12223條的語句,減少了50倍,也就是245條。效率不言而喻了。(實際使用需要結合數據庫索引以及in的問題。)
做到這,想到Excel導入數據庫的時候是不是也會有另外一種優化方法。。。
菜鳥求教,請勘誤。
本文從百度空間搬家到博客園。。
新聞熱點
疑難解答