首页 > 数据库 >sqlsugar 封装 单例模式 多数据库

sqlsugar 封装 单例模式 多数据库

时间:2024-08-29 21:54:02浏览次数:6  
标签:封装 string connectStr dbInfo PlayGround 单例 new public sqlsugar

# PlayGround\.config\dotnet-tools.json


{
  "version": 1,
  "isRoot": true,
  "tools": {
    "csharpier": {
      "version": "0.29.1",
      "commands": [
        "dotnet-csharpier"
      ],
      "rollForward": false
    }
  }
}

PlayGround\.vscode\launch.json


{
    "version": "0.2.0",
    "configurations": [
        {
            // Use IntelliSense to find out which attributes exist for C# debugging
            // Use hover for the description of the existing attributes
            // For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md
            "name": ".NET Core Launch (console)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            // If you have changed target frameworks, make sure to update the program path.
            "program": "${workspaceFolder}/bin/Debug/net9.0/PlayGround.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
            "console": "internalConsole",
            "stopAtEntry": false
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach"
        }
    ]
}

PlayGround\.vscode\tasks.json


{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/Playground.sln",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary;ForceNoAlign"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "publish",
            "command": "dotnet",
            "type": "process",
            "args": [
                "publish",
                "${workspaceFolder}/Playground.sln",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary;ForceNoAlign"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "watch",
            "command": "dotnet",
            "type": "process",
            "args": [
                "watch",
                "run",
                "--project",
                "${workspaceFolder}/Playground.sln"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}

PlayGround\.csharpierrc

PlayGround\appsettings.json


{
  "ConnectionStrings": {
    "AppOne": "Server=localhost;Database=DDD;Trusted_Connection=True;MultipleActiveResultSets=true",
    "MySqlConnection": "Server=localhost;Database=ElectricDDD;Uid=root;Pwd=123456;"
  },
  "DataProvider": "MsSql",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Authentication": {
    "JwtBearer": {
      "SecurityKey": "ELETRICAPIC421AAEE0D114E9C",
      "Issuer": "EletricAPI",
      "Audience": "EletricAPI"
    }
  },
  "CorsOrigins": "http://localhost:9527",
  "AllowedHosts": "*"
}

PlayGround\Entity.cs


public class SugarEntity
{
    // public SugarEntity()
    // {
    // }
}

PlayGround\PlayGround.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
  <PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageReference Include="SqlSugarCore" Version="5.1.4.168-preview11" />
    <PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
  </ItemGroup>

  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <None Update="nlog.config" CopyToOutputDirectory="Always" />
  </ItemGroup>

</Project>

PlayGround\Playground.sln

PlayGround\Program.cs


using System.Data;
using Microsoft.Extensions.Configuration;
using SqlSugarFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        IConfigurationRoot configurationRoot = configurationBuilder.SetBasePath(AppContext.BaseDirectory).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
        IConfigurationSection dbConfigurationSection = configurationRoot.GetSection("ConnectionStrings");
        LongSugarClient longSugarClient = LongSugarClient.GetInstance(DbInfo.MesOne, dbConfigurationSection);
        List<EleTodo> eleTodos = longSugarClient.ExcuteRawSql<EleTodo>("SELECT * FROM [DDD].[dbo].[EleTodo]");
        foreach (var eleTodo in eleTodos)
        {
            System.Console.WriteLine(eleTodo.Name);
        }

        DataTable dataTable = longSugarClient.ExcuteRawSql("SELECT * FROM [DDD].[dbo].[EleTodo]");
        System.Console.WriteLine(dataTable.Rows.Count);

        DataTable dataTable2 = longSugarClient.ExcuteRawSql("SELECT count(*) FROM [DDD].[dbo].[EleTodo]");
        System.Console.WriteLine(dataTable2.Rows[0][0]);


        List<EleTodoCount> eleTodoCounts = longSugarClient.ExcuteRawSql<EleTodoCount>("SELECT count(*) as count FROM [DDD].[dbo].[EleTodo]");
        System.Console.WriteLine(eleTodoCounts.First().Count);

    }
}



PlayGround\run.bat


dotnet run

PlayGround\SqlSugarCore.cs


using System.Data;
using System.Linq.Expressions;
using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace SqlSugarFrameworkCore;

public class DbSettings
{
    public const string AppOne = "AppOne";
    public const string AppDevOne = "AppDevOne";
    public const string AppThreeOne = "AppThreeOne";
    public const string Oracle = "Oracle";
}

public enum DbInfo
{
    MesOne = 1,
    MesDevOne = 2,
    MesThree = 3,
    Oracle = 4,
}

public class LongSugarClient
{
    public static LongSugarClient sugarInstance;
    public static DbInfo curDbInfo;
    public static Dictionary<DbInfo, LongSugarClient> sugarInstances = new Dictionary<DbInfo, LongSugarClient>();

    public static readonly object sugarInstanceLock = new object();
    public SqlSugarClient _db;

    private LongSugarClient(SqlSugarClient sqlSugarClient)
    {
        _db = sqlSugarClient;
    }

    public static LongSugarClient GetInstance(DbInfo dbInfo, IConfigurationSection dbConfigurationSection)
    {
        if (sugarInstances.ContainsKey(dbInfo))
        {
            sugarInstances.TryGetValue(dbInfo, out LongSugarClient sugarInstance);
            return sugarInstance;
        }

        lock (sugarInstanceLock)
        {
            if (sugarInstances.ContainsKey(dbInfo))
            {
                sugarInstances.TryGetValue(dbInfo, out LongSugarClient sugarInstance);
                return sugarInstance;
            }
            GetSugarClient(dbInfo, dbConfigurationSection);
        }
        return sugarInstance;
    }

    private static void GetSugarClient(DbInfo dbInfo, IConfigurationSection dbConfigurationSection)
    {
        if (dbInfo == DbInfo.MesOne)
        {
            string connectStr = dbConfigurationSection.GetSection(DbSettings.AppOne).Value ?? throw new ArgumentNullException($"{DbSettings.AppOne} is misstion");

            System.Console.WriteLine(connectStr);
            CreateSugarClient(dbInfo, connectStr);
        }
        else if (dbInfo == DbInfo.MesDevOne)
        {
            string connectStr = dbConfigurationSection.GetSection(DbSettings.AppDevOne).Value ?? throw new ArgumentNullException($"{DbSettings.AppDevOne} is misstion");
            CreateSugarClient(dbInfo, connectStr);
        }
        else if (dbInfo == DbInfo.MesThree)
        {
            string connectStr = dbConfigurationSection.GetSection(DbSettings.AppThreeOne).Value ?? throw new ArgumentNullException($"{DbSettings.AppThreeOne} is misstion");
            CreateSugarClient(dbInfo, connectStr);
        }
        else if (dbInfo == DbInfo.Oracle)
        {
            string connectStr = dbConfigurationSection.GetSection(DbSettings.Oracle).Value ?? throw new ArgumentNullException($"{DbSettings.Oracle} is misstion");
            CreateSugarClient(dbInfo, connectStr);
        }
    }

    private static void CreateSugarClient(DbInfo dbInfo, string connectStr)
    {
        SqlSugarClient sqlSugar = new SqlSugarClient(
            new ConnectionConfig()
            {
                DbType = SqlSugar.DbType.SqlServer,
                ConnectionString = connectStr,
                IsAutoCloseConnection = true,
            },
            db =>
            {
                //单例参数配置,所有上下文生效
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    //打印日志
                    // Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                };
            }
        );
        sugarInstance = new LongSugarClient(sqlSugar);
        sugarInstances.Add(dbInfo, sugarInstance);
    }


    public DataTable ExcuteRawSql(string sql)
    {
        DataTable dataTable = this._db.SqlQueryable<DataTable>(sql).ToDataTable();
        return dataTable;
    }

    public List<T> ExcuteRawSql<T>(string sql)
        where T : SugarEntity, new()
    {
        List<T> list = this._db.SqlQueryable<T>(sql).ToList();
        return list;
    }

}

PlayGround\TodoEntity.cs


public enum TodoStatus
{
    Undo,
    Done,
}

public class EleTodo : SugarEntity
{
    public EleTodo() { }

    public Guid Id { get; set; }

    public string Name { get; set; }

    public TodoStatus Status { get; set; }

    public string? Remark { get; set; }

    public Guid UserId { get; set; }
}

public class EleTodoCount : SugarEntity
{
    public int Count { get; set; }
}
 

PlayGround\zz.bat


set "scriptPath=%cd%" 
D: && cd D:\dotnet.-script\App\bin\Debug\net8.0\ && D:\dotnet.-script\App\bin\Debug\net8.0\App.exe  "%scriptPath%"   "Question"


  












标签:封装,string,connectStr,dbInfo,PlayGround,单例,new,public,sqlsugar
From: https://www.cnblogs.com/zhuoss/p/18387609

相关文章

  • sqlsugar 单例模式 封装
    usingSystem.Linq.Expressions;usingMicrosoft.Extensions.Configuration;usingSqlSugar;namespaceSqlSugarFrameworkCore;publicclassDbSettings{publicconststringAppOne="AppOne";publicconststringAppDevOne="AppDevOne";pub......
  • SpringBoot把本地的对象封装成为Nacos的配置对象
    你需要有个NacosNacos建立你的配置文件--建议yml文件编写你的yml配置platform:transaction:properties:notifyHost:"http://10.130.1.18:${server.port.cztech-service-gateway}"smsTemplate:"TEM_0029"#订单默认过期时间--分钟defau......
  • python读取配置文件&&简单封装 公共配置文件 config
    之前有做过把爬虫数据写到数据库中的练习,这次想把数据库信息抽离到一个ini配置文件中,这样做的好处在于可以在配置文件中添加多个数据库,方便切换(另外配置文件也可以添加诸如邮箱、url等信息)1.configparser模块python使用自带的configparser模块用来读取配置文件,配置文......
  • pygame封装常用控件,第二日,有滑块的文本显示域
    #coding=utf-8importos,sys,re,timeimportpygameimportrandomfromwin32apiimportGetSystemMetricsfromtkinterimportmessageboxpygame.init()pygame.display.set_caption("我的控件")percent=0.6screen_width=GetSystemMetrics(0)screen_heig......
  • 封装与继承
    1.封装1.1封装的概念:将类的某些信息隐藏在类内部,不允许外部程序直接访问,而是通过该类提供的方法来实现对隐藏信息的操作和访问把尽可能多的东西藏起来,对外提供便捷的接口1.2如何实现封装一,修改属性的可见性(设为private,防止错误的修改)二,创建共有的·getter/setter方法(用......
  • 《C++中的友元:打破封装的神秘力量》
    在C++的编程世界里,友元函数和友元类就像是一把特殊的钥匙,可以打开封装的大门,让特定的函数或类能够访问其他类的私有成员。这一特性在某些情况下具有重要的作用,让我们一起来深入探讨C++中的友元函数和友元类有什么作用。一、热点关注:友元为何引发热议?在面向对象编程中,封......
  • 【设计模式】单例模式(线程安全)
     ......
  • 在做结果集封装时,若结果集表头与成员变量名不一致该如何解决?
    目录1.通过别名映射为一致:as子句2.使用resultMap3.在配置文件中开启适配规则在Score实体类中,我们定义了studentId、courseId、score、status,而在数据库中,我们设置如下:1.通过别名映射为一致:as子句在持久层接口中,我们定义了select1()方法,返回类型为List<Score>。由于......
  • 单例模式 lock 多线程 双重检查锁定机制
    单例模式单例模式publicclassSingleton{//定义一个静态变量来保存类的实例privatestaticSingletonuniqueInstance;//定义一个标识确保线程同步privatestaticreadonlyobjectlocker=newobject();//定义私有构造函数,使外界不能创建该类......
  • 单例模式
    1.单线程单例确保一个类只有一个实例,并提供一个访问它的全局访问点概念拆分(1.一个类只有一个实例2.提供一个全局访问点)publicclassSingleton{privatestaticSingletonsingleton;//定义一个静态变量来保护类的实例publicstaticSingleton......