1.注意事项
MySql注意:
- MYSQL不支持创建表和删除表处理事务,原生事务也一样
- MyISAM?存储引擎不支持事务?需要改成?InnoDB
2.单库事务
static void Main(string[] args)
??????? {
??????????? var db = Sugar.GetInstance();
??????????? try
??????????? {
??????????????? db.Ado.BeginTran();
??????????????? db.Insertable(new Student() { Id = "1", Name ="hpf", SchoolId = 1 }).ExecuteCommand();
?throw new Exception(); //手动抛出异常,回滚Sql
??????????????? db.Ado.CommitTran();
??????????? }
??????????? catch (Exception ex)
??????????? {
??????????????? db.Ado.RollbackTran();
??????????? }
??????????? Console.ReadLine();
??????? }
3.调试事务
- db.ContextId要从事务开始,CURD?和事务结束?必须一致?这个事务才会生效,如果是MYSQL也检查一下表引擎是否支持事务
- SqlsugarClient?可以用变量 var db=外部Db;?所有操作使用db保证一致
- SqlsuagrScope (该对象是线程安全对象,可以单例)可以用单例模式保证一致
项目运行起来的时候,在监视中手动输入 db.ContextId ,以便监控值是否保持不变 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WwmKnK9n-1651193424862)(en-resource://database/1605:1)]
4.语法糖
这种适合没有异常处理的,减少了try?处理
static void Main(string[] args)
??????? {
??????????? var db = Sugar.GetInstance();
??????????? var result = db.UseTran(() =>
??????????? {
??????????????? db.Insertable(new Student() { Id = "2", Name = "hpf", SchoolId= 2 }).ExecuteCommand();
??????????????? //throw new Exception();
??????????????? return true;
??????????? });
??????????? if (result.IsSuccess == false)//事务出现回滚
??????????????? throw result.ErrorException;
??????????? Console.ReadLine();
??????? }
5.异步事务
public class Program
??? {
??????? static async Task Main(string[] args)
??????? {
??????????? var db = Sugar.GetInstance();
??????????? await Test(db);
??????????? Console.ReadLine();
??????? }
??????? public static async Task Test(SqlSugarClient db)
??????? {
??????????? //异步事务
??????????? var result = await db.UseTranAsync(async () =>
??????????? {
??????????????? await db.Insertable(new Student() { Id = "6", Name = "hpf",SchoolId = 2 }).ExecuteCommandAsync();
??????????????? //throw new Exception(); //手动模拟抛异常
??????????? });
??????????? if (result.IsSuccess == true)
??????????????? Console.WriteLine("添加成功");
??????????? else
??????????????? Console.WriteLine("添加失败");
??????? }
??? }
6.设置事务隔离级别
try
{
????db.Ado.BeginTran(IsolationLevel.ReadCommitted);
?????????
????????//业务代码??
?????????
????db.Ado.CommitTran();
}
catch?(Exception?ex)
{
????db.RollbackTran();
????throw?ex;
}
文档参考:数据事务
|