熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

總結:ADO.NET在開發中的部分使用方法和技巧[9]

2022-06-13   來源: .NET編程 

  該存儲過程使用 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
}
}
}

[]  []  []  []  []  []  []  []  []  


From:http://tw.wingwit.com/Article/program/net/201311/15087.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.