啊鑫
2024-10-18 b687c2bac305b570e81a650a64a4a7d440671c4b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using MES.Service.util;
using SqlSugar;
 
namespace MES.Service.DB;
 
public class SqlSugarHelper
{
    private static readonly string _connectionString =
        AppsettingsUtility.Settings.DataBaseConn; // 这里替换成你的实际连接字符串
 
    public static SqlSugarClient GetInstance()
    {
        var db = new SqlSugarClient(new ConnectionConfig
        {
            ConnectionString = _connectionString,
            DbType = DbType.Oracle,
            IsAutoCloseConnection = true, //开启自动释放模式和EF原理一样我就不多解释了
            InitKeyType = InitKeyType.Attribute
        });
 
 
        //调式代码 用来打印SQL 
        db.Aop.OnLogExecuting = (sql, pars) =>
        {
            Console.WriteLine(
                UtilMethods.GetSqlString(DbType.Oracle, sql, pars));
        };
        return db;
    }
 
    public static int UseTransactionWithOracle(Func<SqlSugarClient, int> action)
    {
        using (var db = GetInstance())
        {
            try
            {
                db.Ado.BeginTran(); // 开始事务
                var affectedRows = action.Invoke(db); // 执行传入的操作并获取受影响的行数
                db.Ado.CommitTran(); // 提交事务
                return affectedRows; // 返回受影响的行数
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran(); // 回滚事务
                throw ex;
            }
        }
    }
}