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

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:

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();
}

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

 
批处理也是比较简单的。

相关文章:

  • 2021-10-18
  • 2021-11-27
  • 2022-02-27
  • 2021-12-16
  • 2022-01-24
  • 2021-11-04
  • 2021-08-24
  • 2021-09-24
猜你喜欢
  • 2021-05-30
  • 2021-09-03
  • 2022-01-29
  • 2021-10-29
  • 2022-01-07
  • 2021-06-24
  • 2021-10-27
相关资源
相似解决方案