使用TransactionScope时设置数据库连接

时间:2010-04-26 21:05:17

标签: vb.net database-connection transactionscope

是否必须在TransactionScope

中设置数据库连接

或者我可以在ctor中设置它,然后让实例方法创建TransactionScope吗?

编辑:,例如

Public Sub New()
   Dim conn = new SqlConnection(...connection string)
Public Sub SomeClassMethod()
   using ts as new TransactionScope
      //conn has already been initialized
      //so, here you can set commands, ExecuteDataSet, etc.

vs

Public Sub New()
   //nothing here
Public Sub SomeClassMethod()    
   using ts as new TransactionScope
      conn = new SqlConnection(...connection string)
      set commands, ExecuteDataSet, etc.

问题是,您是否需要在创建TransactionScope后创建与数据库的连接,还是可以在之前完成?

1 个答案:

答案 0 :(得分:0)

如果您希望SqlConnection处于事务处理之下,则需要在TransactionScope下创建它。

using(TransactionScope scope = new TransactionScope())
{
  SqlConnection x = new SqlConnestion("....");
  x.Open();
  ....your code... SQlCommands etc....
  x.Close();
  scope.Complete();
}