C#通过sqlsugar插入数据到postgresql

1.测试通过sql语句保存json数据,使用jsonb字段

复制代码
        public async Task<string> SavePostgreSQLTest(int count = 0,string files="")
        {
            string SqlStr = "";
            string jsonParamStr = JsonConvert.SerializeObject(new
            {
                count = count,
                file = $"{files}",
            });

         
            await Task.Run(() =>
        {
            SqlStr = "INSERT INTO \"MyObj\".mytable (id, name, age,jsonb_result ,json_result) VALUES (@id, @Name, @Age,@JsonbResult::jsonb,@JsonResult)";
            var parameters = new List<SugarParameter> {
        new SugarParameter("@id", 5),
        new SugarParameter("@Name", "周七"),
        new SugarParameter("@Age", 29),
                new SugarParameter("@JsonbResult", jsonParamStr),
        new SugarParameter("@JsonResult", jsonParamStr)
};

            try
            {
                SqlSugarHelperV1.ExcuteSqlString(SqlStr, parameters);
            }
            catch (Exception ex)
            {
                Log.Logger.Error($"LinkAsiaDB InitTireGlueingPLYDB 异常 {ex.Message} {ex.StackTrace}");
            }
        });

            return "jsonStr";
        }

2.sqlsugarhelper代码如下

复制代码
using SqlSugar;

namespace aaa.Helper.DB
{
    public static class SqlSugarHelperV1
    {
        private static SqlSugarScope _db;

        static SqlSugarHelperV1()
        {
            string mysqlConnectionStr = AppSettingsHelper.Configuration["DB:PostgreSQLConnStr"] ?? "";
            // 初始化数据库连接
            _db = new SqlSugarScope(new ConnectionConfig()
            { 
               
                ConnectionString = mysqlConnectionStr,// "server=localhost;port=3306;database=testdb;user=root;password=123456;",
                DbType = SqlSugar.DbType.PostgreSQL,
                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($"PostgreSQL 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);
        }
    }
}

postgresql的数据库表字段

下面是查询jsonb字段中的json中key的value值

复制代码
 select *,jsonb_result ->'name' as name1 from "MyObj".mytable;
相关推荐
唐青枫2 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6252 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902112 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠3 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫5 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech5 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf7 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6257 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech7 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
LDR0068 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言