C#使用SqlSugar操作mysql数据库

1.安装SqlSugar我的环境是.net 10.

2.编写helper类

复制代码
using SqlSugar;

namespace xxx.Helper.DB
{
    public static class SqlSugarHelper
    {
        private static SqlSugarScope _db;

        static SqlSugarHelper()
        {
            string mysqlConnectionStr = AppSettingsHelper.Configuration["DB:MySQLConnStr"] ?? "";
            // 初始化数据库连接
            _db = new SqlSugarScope(new ConnectionConfig()
            { 
               
                ConnectionString = mysqlConnectionStr,// "server=localhost;port=3306;database=testdb;user=root;password=123456;",
                DbType = SqlSugar.DbType.MySql,
                IsAutoCloseConnection = true, // 自动关闭连接
                InitKeyType = InitKeyType.Attribute, // 从特性读取主键和自增列信息
                //ConfigureExternalServices = new ConfigureExternalServices()
                //{
                //    EntityService = (c, p) =>
                //    {
                //        // 设置列的默认值
                //        if (p.IsPrimarykey == false && p.PropertyName == "Id")
                //        {
                //            p.IsIgnore = true; // 忽略非主键的Id列
                //        }
                //    }
                //}
            });

            //// 设置AOP事件
            //_db.Aop.OnLogExecuting = (sql, pars) =>
            //{
            //    Console.WriteLine($"SQL: {sql}");
            //    Console.WriteLine($"Parameters: {string.Join(", ", pars.Select(p => $"{p.ParameterName}:{p.Value}"))}");
            //};

            _db.Aop.OnError = (exp) =>
            {
                Console.WriteLine($"SQL Error: {exp.Sql}");
                Console.WriteLine($"Error Message: {exp.Message}");
            };
        }

        // 获取数据库实例
        public static SqlSugarScope Db => _db;

        // 查询多个对象(使用 SQL)
        public static List<T> GetList<T>(string sql, object parameters = null) where T : class, new()
        {
            return _db.Ado.SqlQuery<T>(sql, parameters);
        }
        public static void ExcuteSqlString(string sql, object parameters = null)    
        {
              _db.Ado.ExecuteCommand(sql, parameters);
        }
    }
}
相关推荐
神探小白牙9 分钟前
echarts,3d堆叠图
android·3d·echarts
李白的天不白22 分钟前
如何项目发布到github上
android·vue.js
summerkissyou198724 分钟前
Android-RTC、NTP 和 System Time(系统时间)
android
小书房31 分钟前
Kotlin使用体验及理解1
android·开发语言·kotlin
撩得Android一次心动1 小时前
Android Navigation 组件全面讲解
android·jetpack·navigation
向阳是我1 小时前
Flutter Android 编译错误修复:JVM Target Compatibility 不一致问题记录
android·jvm·flutter
Kapaseker1 小时前
我想让同事知道我很懂 Compose 怎么办?
android·kotlin
小肝一下2 小时前
3. 数据类型
android·数据库·mysql·adb
a2591748032-随心所记2 小时前
android拆解super.img内容
android·linux·运维·服务器
Mr_pyx2 小时前
MySQL性能优化:深入理解索引原理与查询优化实战
android