批处理就是提交的脚本不是马上执行,而是到一定数量才提交。
还是先上例子
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();
}

效果和第一个例子是一样的。

 
批处理也是比较简单的。
posted on 2010-01-30 12:49  steven hu  阅读(4572)  评论(4编辑  收藏  举报