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);
        }
    }
}
相关推荐
alexhilton14 小时前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
冬奇Lab17 小时前
InputManagerService:输入事件分发与ANR机制
android·源码阅读
张小潇20 小时前
AOSP15 Input专题InputManager源码分析
android·操作系统
RdoZam1 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
奥陌陌1 天前
android 打印函数调用堆栈
android
用户985120035831 天前
Compose Navigation 3 深度解析(二):基础用法
android·android jetpack
恋猫de小郭1 天前
Android 官方正式官宣 AI 支持 AppFunctions ,Android 官方 MCP 和系统级 OpenClaw 雏形
android·前端·flutter
黄林晴1 天前
Android 17 Beta 2,隐私这把锁又拧紧了
android
Kapaseker1 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
bqliang1 天前
Compose 媒体查询 (Media Query API) 🖱️👇🕹️
android·android jetpack