如何在 Using{} 块中使用 Transaction
How to use Transaction inside Using{} block
目前在执行任何与数据库相关的代码时,我使用以下结构:
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);
}
现在我想在上面合并事务 structure.How 我是否使用 Using 块以正确的方式进行操作。请用正确的代码片段进行解释。
如果您只是阅读记录 (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 块,在该块中以正确的顺序处理事务和连接
目前在执行任何与数据库相关的代码时,我使用以下结构:
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);
}
现在我想在上面合并事务 structure.How 我是否使用 Using 块以正确的方式进行操作。请用正确的代码片段进行解释。
如果您只是阅读记录 (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 块,在该块中以正确的顺序处理事务和连接