1
yhj
2024-07-24 5e5d945e91568b973faa27d8ab0bcef99fc4a6c5
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
50
51
52
53
54
55
using System;
using System.Linq;
using SqlSugar;
 
namespace CSFramework.DB
{
    public class SqlSugarHelper
    {
        private static readonly string _connectionString =
            "Data Source=43.142.96.171;Initial Catalog=CSFrameworkV5_Normal;User ID=gsmesuser;Password =123456;"; // 这里替换成你的实际连接字符串
 
        public static SqlSugarClient GetInstance()
        {
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = _connectionString,
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true, //开启自动释放模式和EF原理一样我就不多解释了
                InitKeyType = InitKeyType.Attribute
            });
 
 
            //调式代码 用来打印SQL 
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql + "\r\n" +
                                  db.Utilities.SerializeObject(
                                      pars.ToDictionary(it => it.ParameterName,
                                          it => it.Value)));
                // LogHelper.LogWrite(sql + "\r\n" +Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
            };
            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;
                }
            }
        }
    }
}