我正在使用Here中的ado.net帮助程序类。我不知道如何使用帮助程序使用事务。以下是我尝试过的代码。我做对了吗?我总是遇到This SqlTransaction has completed; it is no longer usable.
错误。
Adodb.ConnectionString = "...";
Adodb db = new Adodb();
SqlTransaction trans = db.BeginTransaction();
try
{
string qry = "UPDATE PSCHCounter SET SeqNo = '0' WHERE CountID = 'PCSTL'";
db.ExecNonQuery(qry);
string qry1 = "UPDATE PSCHCounter SET SeqNo = '1' WHERE CountID = 'GJNLP'";
db.ExecNonQuery(qry1);
// Commit
trans.Commit();
}
catch (Exception ex)
{
try
{
// Rollback
trans.Rollback();
// Log exception
}
catch (Exception ex2)
{
// Log exception
}
}
finally
{
// Close db connection
db.Dispose();
}
谢谢。
答案 0 :(得分:1)
问题是您是在调用trans.Commit()
而不是db.Commit()
。这对我有用:
AdoHelper.ConnectionString = "...";
using (AdoHelper db = new AdoHelper())
{
// Start the transaction
db.BeginTransaction();
try
{
db.ExecNonQuery("UPDATE FeedItems SET Title = 'Test3' WHERE Id = 456");
db.ExecNonQuery("UPDATE FeedItems SET Title = 'Test4' WHERE Id = 457");
// Commit
db.Commit();
}
catch (Exception ex)
{
db.Rollback();
}
}