C#事务操作数据库例子

2024-11-16 03:14:56
推荐回答(1个)
回答(1):

DBTransaction Db = new DBTransaction();
//获取连接
SqlConnection conn = Db.GetConnection();
//获取事务
SqlTransaction trans = Db.GetTransaction(conn);
//定义一个布尔型变量
bool isUseExamTemplate = false;

try
{
for (int i = 0; i < examNormTemplate.Count; i++)
{
ExamNormLinkEntity item = (ExamNormLinkEntity)examNormTemplate[i];

isUseExamTemplate = examMethod.Add(item, conn, trans);
}
//提交事务
Db.Commit(trans);

}
catch(Exception e)
{
//回滚事务
Db.Rollback(trans);
throw e;
}
finally
{
//关闭连接
Db.Close(conn);
}