如何在 Using{} 块中使用 Transaction [英] How to use Transaction inside Using{} block
问题描述
目前在做任何与数据库相关的代码时,我使用以下结构:
At present while doing any database related code i use the following structure:
try
{
using(FBConnection con = new FBConnection('connectionstringhere'))
{
con.Open();
using(FBCommand cmd = FBCommand("qryString",con))
{
cmd.Parameters.Add("paramSql", FbDbType.Date).Value ="somevalue";
cmd.CommandType = CommandType.Text;
using(FBDatareader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
//some code here
}
}
}
}
}
catch(FBException ex)
{
MessageBox.Show(ex.Message);
}
现在我想将事务合并到上述结构中.我如何使用 Using 块以正确的方式进行操作.请用正确的代码片段解释.
Now i want to incorporate Transaction in the above structure.How do i do it proper way using Using block. Please explain with proper code snippet.
推荐答案
如果您只是读取记录 (ExecuteReader),则不需要事务,但是这可能是使用 TransactionScope 类
You don't need a Transaction if you are just reading records (ExecuteReader) however this could be an approach using the 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 块,在该块中您以正确的顺序处理事务和连接
Not sure about the behavior or the FBConnection object in case of exceptions so better going on a traditional finally block in which you dispose the transaction and the connection in the correct order
这篇关于如何在 Using{} 块中使用 Transaction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!