批處理就是提交的腳本不是馬上執行,而是到一定數量才提交。
還是先上例子
using (DbBatch batch = DbSession.Default.BeginBatchConnection())
{
batch.Update<Products>(Products._.ProductName, "apple", Products._.ProductID == 1);
batch.Update<Products>(Products._.ProductName, "pear", Products._.ProductID == 2);
batch.Update<Products>(Products._.ProductName, "orange", Products._.ProductID == 3);
}
生成的sql:
Text:
UPDATE [Products] SET [ProductName]=@3d40ca14f83644f18269874c99e621a5
WHERE [Products].[ProductID] = @50999b135fbf4f068f89bda7ab341ac3;
UPDATE [Products] SET [ProductName]=@fe1ea91dd6e14260813ea19abbc245eb
WHERE [Products].[ProductID] = @6bef4d78041549fa817c3363bd847d41;
UPDATE [Products] SET [ProductName]=@075f1b4639c446be88bfc33638b1f754
WHERE [Products].[ProductID] = @588a5481ff3d4ff58fc304293173b6ab;
Parameters:
@3d40ca14f83644f18269874c99e621a5[String] = apple
@50999b135fbf4f068f89bda7ab341ac3[Int32] = 1
@fe1ea91dd6e14260813ea19abbc245eb[String] = pear
@6bef4d78041549fa817c3363bd847d41[Int32] = 2
@075f1b4639c446be88bfc33638b1f754[String] = orange
@588a5481ff3d4ff58fc304293173b6ab[Int32] = 3
默認是10條sql執行一次。也可以自定義。
DbBatch batch = DbSession.Default.BeginBatchConnection(20)
這樣就設置了20條sql執行一次。
並可以設置內部事務級別.
DbBatchbatch = DbSession.Default.BeginBatchConnection(20, IsolationLevel.ReadCommitted)
也可強制性執行:
using (DbBatch batch = DbSession.Default.BeginBatchConnection())
{
batch.Update<Products>(Products._.ProductName, "apple", Products._.ProductID == 1);
batch.Update<Products>(Products._.ProductName, "pear", Products._.ProductID == 2);
batch.Execute();
batch.Update<Products>(Products._.ProductName, "orange", Products._.ProductID == 3);
}
執行batch.Execute(),就會將之前的sql腳本先提交。
生成的sql:
Text:
UPDATE [Products] SET [ProductName]=@1ae514d0db3247acb196b8d55110a8e8
WHERE [Products].[ProductID] = @c694d46594324eec9db0d1e26a3ea499;
UPDATE [Products] SET [ProductName]=@4b1d4e07b6cc45d994e65c5eeac12619
WHERE [Products].[ProductID] = @58fa8ceaede745f0ac541d5c45574309;
Parameters: @1ae514d0db3247acb196b8d55110a8e8[String] = apple
@c694d46594324eec9db0d1e26a3ea499[Int32] = 1
@4b1d4e07b6cc45d994e65c5eeac12619[String] = pear
@58fa8ceaede745f0ac541d5c45574309[Int32] = 2
Text:
UPDATE [Products] SET [ProductName]=@c3a36b7a94754cd884ee27d4e42199a5
WHERE [Products].[ProductID] = @550ebc4788f54105ababe5d6bdc9cf2a;
Parameters: @c3a36b7a94754cd884ee27d4e42199a5[String] = orange
@550ebc4788f54105ababe5d6bdc9cf2a[Int32] = 3
看輸出的腳本分兩次執行的。
try catch的寫法如下:
DbBatch batch = DbSession.Default.BeginBatchConnection();
try
{
batch.Update<Products>(Products._.ProductName, "apple1", Products._.ProductID == 1);
batch.Update<Products>(Products._.ProductName, "pear1", Products._.ProductID == 2);
batch.Update<Products>(Products._.ProductName, "orange1", Products._.ProductID == 3);
}
catch
{
//do something
}
finally
{
batch.Close();
}
效果和第一個例子是一樣的。
批處理也是比較簡單的。