ADO.NET 수동 트랜잭션을 코딩하는 방법
다음 코드에서는 트랜잭션으로 예금 전송 작업을 보호하기 위해 SQL Server .NET Data Provider에서 제공되는 트랜잭션 지원의 장점을 활용하는 방법을 보여 줍니다. 이 작업은 동일 데이터베이스에 있는 두 계정 간에 예금을 전송합니다.
public void TransferMoney( string toAccount, string fromAccount, decimal amount )
{
using ( SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=SimpleBank" ) )
{
SqlCommand cmdCredit = new SqlCommand("Credit", conn );
cmdCredit.CommandType = CommandType.StoredProcedure;
cmdCredit.Parameters.Add( new SqlParameter("@AccountNo", toAccount) );
cmdCredit.Parameters.Add( new SqlParameter("@Amount", amount ));
SqlCommand cmdDebit = new SqlCommand("Debit", conn );
cmdDebit.CommandType = CommandType.StoredProcedure;
cmdDebit.Parameters.Add( new SqlParameter("@AccountNo", fromAccount) );
cmdDebit.Parameters.Add( new SqlParameter("@Amount", amount ));
conn.Open();
// Start a new transaction
using ( SqlTransaction trans = conn.BeginTransaction() )
{
// Associate the two command objects with the same transaction
cmdCredit.Transaction = trans;
cmdDebit.Transaction = trans;
try
{
cmdCredit.ExecuteNonQuery();
cmdDebit.ExecuteNonQuery();
// Both commands (credit and debit) were successful
trans.Commit();
}
catch( Exception ex )
{
// transaction failed
trans.Rollback();
// log exception details . . .
throw ex;
}
}
}
}
'C#.NET DB' 카테고리의 다른 글
| [IMAGE] 데이터베이스에 이미지 저장하기 (1) | 2010.01.07 |
|---|---|
| [ SqlDataSource , FilterExpression ] 초간단 데이터검색방법 , 필터링 사용 설정 (0) | 2009.12.15 |
| [DataTable] 데이타테이블 간단한 사용법 및 검색방법 (0) | 2009.12.15 |
| [DataSet]간단한 DataAdapter와 DataSet 만들기 (0) | 2009.12.15 |
| [OleDbDataAdapter] 업데이트 , 삭제 , 셀렉트 속성 (0) | 2009.12.15 |
| [MSDN 트렌젝션]TransactionScope (0) | 2009.12.15 |
| DataTable 데이터 xml로 저장하기 (0) | 2009.12.15 |
| [SqlDataSource] 웹 서버 컨트롤 개요 (0) | 2009.05.20 |
| [트렌젝션]TransactionScope (0) | 2009.05.20 |
| 웹에서 간단하게 오라클 쿼리하기 (0) | 2009.05.19 |