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);
        }
    }
}
相关推荐
g105655913940 分钟前
LAMP博客平台Wordpress实战
android·mysql·nginx·php
hunterandroid2 小时前
[Android 从零到一] Compose LazyColumn 性能优化:key、稳定性与重组治理
android·前端
pengyu2 小时前
【Kotlin 协程修仙录 · 元婴境 · 中阶】 | 操作符真解:Flow 中间操作符与数据流变幻术
android·kotlin
pengyu3 小时前
【Kotlin 协程修仙录 · 元婴境 · 初阶】 | 冷流初啼:Flow 的基础与响应式编程的入门
android·kotlin
wawo003 小时前
Kuikly实践-从Android compose迁移到kuikly compose
android
Carson带你学Android5 小时前
Android 版 MCP 正式登场:AppFunctions
android·ai编程·jetbrains
古法安卓8 小时前
Android-Direct Boot 阶段与 getFilesDir() 路径变更问题深度分析
android·java·android studio
阿巴斯甜8 小时前
Android Studio Detekt 使用
android
杉氧9 小时前
Flutter 跨平台多端适配与 Android/iOS 一键自动化打包发布
android·前端·flutter
Super 含9 小时前
Android 包体积优化(一):APK 到底大在哪里?从 APK 结构到体积分析
android·ide·vscode