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);
        }
    }
}
相关推荐
雨白36 分钟前
C 语言字符串:从字符数组、指针到核心操作实战
android
Java小白笔记1 小时前
MySQL中存储过程大表分批删除历史数据
android·mysql·adb
aidou13142 小时前
Kotlin中沉浸式状态栏显示布局
android·kotlin·windowmanager·沉浸式状态栏·insetslistener·insetscompat·systembars
我命由我123452 小时前
Android 构建项目问题:XML 片段出错,com.ctc.wstx.exc.WstxUnexpectedCharException
android·xml·android studio·android jetpack·android-studio·android runtime
阿pin3 小时前
Android随笔-pipe是什么?
android·linux·pipe
帅次3 小时前
Android 高级工程师面试:Flow 与状态流 近1年高频追问 22 题
android·面试·职场和发展
雨季余静3 小时前
RustDesk Android APK 从零编译全步骤
android
辰合软件3 小时前
通达OA配置文件详解
android·adb
辰合软件3 小时前
通达OA目录结构与核心文件解析
android·数据库·oracle
通玄3 小时前
Jetpack Compose 入门系列(八):Compose 中的副作用处理
android