我想在我的代码中插入一个函数,即begin,commit和rollback trans,因为数据容易出错。我的代码是这样的:
clsDBConnect dbConn = new clsDBConnect();
SqlCommand CMD;
SqlDataReader Reader;
private void Save()
{
CMD = new SqlCommand("SELECT * FROM tblEmployees", dbConn.connection);
Reader = CMD.ExecuteReader();
while (Reader.Reader())
{
while(variable1 != variable2)
{
//Lots of CMD.ExecuteNonQuery();
//Lots of Reader
//Lots of computation
variable1 += 1;
}
}
}
如何在循环期间发生错误时回滚插入和更新?
谢谢!
答案 0 :(得分:0)
事务处理以这样的方式完成:
DbTransaction trans = dbConn.BeginTransaction();
try
{
// ... do your stuff...
// Last line of the try-block... if you are still alive here, commit
trans.Commit();
}
catch (Exception e)
{
// Something evil happened... Rollback
trans.Rollback();
}