我正在使用SQL Server 2012,同一个数据库内有多个SQL连接在TransactionScope
的Using块中。但是,如果第一个更新SQL操作没有得到期望的输出,则我会跳过下一个调用SQL操作,并且在Using
块结束时也不会调用TransactionScope.Complete
。
我正在使用SQL Server 2012,同一个数据库内有多个SQL连接在TransactionScope
的Using块中。但是,如果第一个更新SQL操作没有得到期望的输出,则我会跳过下一个调用SQL操作,并且在Using
块结束时也不会调用TransactionScope.Complete
。
未调用事务完成将导致事务中止,这就是为什么调用 transaction.complete();
是一种非常好的实践。
会发生的情况是,事务管理器将其解释为系统故障并抛出异常(我曾经遇到过这种情况,很不好),但是,需要注意的是,这并不保证事务将被提交,因此您还需要调用 commit。
例如:
using (TransactionScope scope = new TransactionScope())
{
using (SqlConnection connection1 = new SqlConnection(connectString1))
{
// Opening the connection automatically enlists it in the
// TransactionScope as a lightweight transaction.
connection1.Open();
// Create the SqlCommand object and execute the first command.
SqlCommand command1 = new SqlCommand(commandText1, connection1);
returnValue = command1.ExecuteNonQuery();
writer.WriteLine("Rows to be affected by command1: {0}", returnValue);
// If you get here, this means that command1 succeeded. By nesting
// the using block for connection2 inside that of connection1, you
// conserve server and network resources as connection2 is opened
// only when there is a chance that the transaction can commit.
using (SqlConnection connection2 = new SqlConnection(connectString2))
{
// The transaction is escalated to a full distributed
// transaction when connection2 is opened.
connection2.Open();
// Execute the second command in the second database.
returnValue = 0;
SqlCommand command2 = new SqlCommand(commandText2, connection2);
returnValue = command2.ExecuteNonQuery();
writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
}
}
// The Complete method commits the transaction. If an exception has been thrown,
// Complete is not called and the transaction is rolled back.
scope.Complete();
}
TransactionScope
对象最初创建了工作。否则,提交将发生无论何时调用commit
行。