该存储过程使用 BEGIN TRANSACTIONCOMMIT TRANSACTION 和 ROLLBACK TRANSACTION 语句来手动控制该事务
如何编写事务性 NET 类
以下示例代码显示了三个服务性 NET 托管类这些类经过配置以执行自动事务处理每个类都使用 Transaction 属性进行了批注该属性的值确定是否应该启动新的事务流或者该对象是否应该共享其直接调用方的事务流这些组件协同工作来执行银行资金转帐任务Transfer 类被使用 RequiresNew 事务属性进行了配置而 Debit 和 Credit 被使用 Required 进行了配置结果所有这三个对象在运行时都将共享同一事务
using System;
using SystemEnterpriseServices;
[Transaction(TransactionOptionRequiresNew)]
public class Transfer : ServicedComponent
{
[AutoComplete]
public void Transfer( string toAccount
string fromAccount decimal amount )
{
try
{
// Perform the debit operation
Debit debit = new Debit();
debitDebitAccount( fromAccount amount );
// Perform the credit operation
Credit credit = new Credit();
creditCreditAccount( toAccount amount );
}
catch( SqlException sqlex )
{
// Handle and log exception details
// Wrap and propagate the exception
throw new TransferException( Transfer Failure sqlex );
}
}
}
[Transaction(TransactionOptionRequired)]
public class Credit : ServicedComponent
{
[AutoComplete]
public void CreditAccount( string account decimal amount )
{
try
{
using( SqlConnection conn = new SqlConnection(
Server=(local); Integrated Security=SSPI; database=SimpleBank) )
{
SqlCommand cmd = new SqlCommand(Credit conn );
cmdCommandType = CommandTypeStoredProcedure;
cmdParametersAdd( new SqlParameter(@AccountNo account) );
cmdParametersAdd( new SqlParameter(@Amount amount ));
connOpen();
cmdExecuteNonQuery();
}
}
}catch( SqlException sqlex ){
// Log exception details here
throw; // Propagate exception
}
}
[Transaction(TransactionOptionRequired)]
public class Debit : ServicedComponent
{
public void DebitAccount( string account decimal amount )
{
try
{
using( SqlConnection conn = new SqlConnection(
Server=(local); Integrated Security=SSPI; database=SimpleBank) )
{
SqlCommand cmd = new SqlCommand(Debit conn );
cmdCommandType = CommandTypeStoredProcedure;
cmdParametersAdd( new SqlParameter(@AccountNo account) );
cmdParametersAdd( new SqlParameter(@Amount amount ));
connOpen();
cmdExecuteNonQuery();
}
}
catch (SqlException sqlex)
{
// Log exception details here
throw; // Propagate exception back to caller
}
}
}
[] [] [] [] [] [] [] [] []