目前在执行任何与数据库相关的代码时,我使用以下结构:
Thread
现在我想在上面的结构中包含Transaction。如何使用Using block以正确的方式进行。请使用正确的代码段解释。
答案 0 :(得分:1)
如果您只是阅读记录(ExecuteReader),则不需要交易,但这可能是使用TransactionScope class
的方法try
{
using(TransactionScope scope = new TransactionScope())
using(FBConnection con = new FBConnection('connectionstringhere'))
{
con.Open();
...
scope.Complete();
}
}
catch(FBException ex)
{
// No rollback needed in case of exceptions.
// Exiting from the using statement without Scope.Complete
// will cause the rollback
MessageBox.Show(ex.Message);
}
标准方法可以写成
FBTransaction transaction = null;
FBConnection con = null;
try
{
con = new FBConnection('connectionstringhere');
con.Open();
transaction = con.BeginTransaction();
...
transaction.Commit();
}
catch(FBException ex)
{
MessageBox.Show(ex.Message);
if(transaction!=null) transaction.Rollback();
}
finally
{
if(transaction != null) transaction.Dispose();
if(con != null) con.Dispose();
}
在异常的情况下不确定行为或FBConnection对象,所以更好地进行传统的finally块,在该块中以正确的顺序处理事务和连接