public
bool
Transfer(
int
transactionAmount,
int
sourceAccount,
int
destinationAccount)
{
bool
result
=
false
;
//
CreatetheDatabaseobject,usingthedefaultdatabaseservice.The
//
defaultdatabaseserviceisdeterminedthroughconfiguration.
Databasedb
=
DatabaseFactory.CreateDatabase();
//
Twooperations,onetocreditanaccount,andonetodebitanother
//
account.
string
sqlCommand
=
"
CreditAccount
"
;
DBCommandWrappercreditCommandWrapper
=
db.GetStoredProcCommandWrapper(sqlCommand);
creditCommandWrapper.AddInParameter(
"
@AccountID
"
,DbType.Int32,sourceAccount);
creditCommandWrapper.AddInParameter(
"
@Amount
"
,DbType.Int32,transactionAmount);
sqlCommand
=
"
DebitAccount
"
;
DBCommandWrapperdebitCommandWrapper
=
db.GetStoredProcCommandWrapper(sqlCommand);
debitCommandWrapper.AddInParameter(
"
@AccountID
"
,DbType.Int32,destinationAccount);
debitCommandWrapper.AddInParameter(
"
@Amount
"
,DbType.Int32,transactionAmount);
using
(IDbConnectionconnection
=
db.GetConnection())
{
connection.Open();
IDbTransactiontransaction
=
connection.BeginTransaction();
try

{
//
Creditthefirstaccount
db.ExecuteNonQuery(creditCommandWrapper,transaction);
//
Debitthesecondaccount
db.ExecuteNonQuery(debitCommandWrapper,transaction);
//
Committhetransaction
transaction.Commit();
result
=
true
;
}
catch

{
//
Rollbacktransaction
transaction.Rollback();
}
connection.Close();
return
result;
}
在这段例子代码中,其核心就是关于 IDbTransaction的使用。
本文介绍了一个转账功能的实现方法,通过使用IDbTransaction确保了数据库操作的原子性。具体包括创建数据库连接、执行存储过程来增减账户余额以及事务的提交与回滚。
302

被折叠的 条评论
为什么被折叠?



