Java教程

sqlSugar 简单封装及使用案例

本文主要是介绍sqlSugar 简单封装及使用案例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

近几天,老家河南遭受了近百年一遇的大暴雨,城市内涝严重,希望家乡人挺住,全国人民期待河南尽快好起来,天空放晴。

在此,仅以一篇郑州地铁五号线遭受暴雨侵袭的帖子作为记录。

一个女孩子写在死里逃生后:
今天郑州暴雨,下午四点物业通知要停电所以需要尽快下班,我和同事下楼后发现门口积水已到膝盖,同事说硬着头皮过吧,我犹豫了一下不敢过,所以没有过去,又等了一个多小时终究还是不想在公司留宿,还是淌着到大腿的水过去了,刚坐上地铁以为噩梦结束了,结果地铁刚过了一站,开往第二站的时候就停在中间了!走不动了,车厢就开始慢慢的往里渗水,但是还不太多,我们就在等怎么办?所有人都傻了,后来地铁的工作人员安排我们慢慢撤离,刚走了没多远,又要求我们回去,因为前方的水全部漫过来了,等全部人员上车后车厢的水已经到腰部了,可是噩梦还没有结束,车外面的水一直在涨,也一直在从门缝里往里渗着,慢慢的水越来越多,我们能站在座位上都站在座位上,最后站在座位上水都到胸口了,我真的害怕了,可是最恐怖的不是水而是车厢里的空气越来越少,好多人都出现了呼吸困难的症状,我听到一个阿姨给家人交代银行卡号,交代家里的事情,我想我是不是也要交代一下呢?当时想联系的人很多,想说的事情也很多,但是最后都没有说出口,只能妈妈发了一句,妈妈我可能快不行了,我有点害怕,但是妈妈回过来电话我也不知道说啥,只说还在等救援,就挂了。从六点到八点半一直都处在崩溃的边缘,慢慢的也不用崩溃了,因为我也因为缺氧晕倒了,就在这个时候我妈妈给我打个电话,手机的震动叫醒了我,和妈妈说了两句,有个救援队的叔叔联系上了,我告诉他我们缺氧快不能呼吸了,叔叔说救援队都到了正在想办法,就在这个时候车顶传来了救命的脚步声,有人来了,消防队的叔叔在使劲的砸车厢的玻璃,一下两下无数下,终于砸开了两扇玻璃,有空气了,我们可以恢复呼吸了!然后就听到车厢前面传来越来越多的声音,救援队终于来了,真正遇到生死的时刻才更能体现人性的美好,这么长时间肯定有很多人熬不住了,到处可以听见互相安慰的声音,有获救的机会了,每个人都在喊着让晕倒的人先走,两个男生架着一个晕倒的人,每个人都上去扶一把,把每个晕倒的人都先救出去,然后所有的男生说女生先走,然后男生真的站在两边等着让女生先走,即使是情侣都放开了彼此的手,让女生先走,男生们在后面一个拉着一个女生走,我头晕走不动了,不过停在哪里,不管男生女生都会说一句,你靠着我就可以,看看好多男生和消防员叔叔一直泡在水里,接应一个又一个女生出去,真的是觉得很庆幸,生在华夏生在一个有爱的国度,遇到善良可爱的人,这是我有生以来第一次离死亡那么近,原来只是嘴上说说谁知道明天和意外哪个先来,这次真的是遇到了,原来意外真的会来,真的是害怕了,如果今天真的出不来了,我会很后悔,后悔有太多的事情没有做,后悔太多人没有见,再也不能吃我最爱的麻辣火锅了,更后悔没有和爸爸妈妈奶奶弟弟说句我爱你们,死里逃生后这种感觉更加深刻,既然幸运的我活下来了,那么以后一定要好好的享受生活,好好的珍惜眼前的人和事!好多人发信息关心我,十万分的感谢大家!谢谢!!

好了,祝福河南好起来的同时,我们也进入正题,Sugar的简单封装

新建一个类库,增加类:SugarDbContext

using SqlSugar;
using System;
using System.Linq;

namespace AppSugarContext
{
    public class SugarDbContext
    {
        /// 获取连接字符串        
       // private static string Connection = ConfigCommon.Get("WuAnDBContext");
        private static string Connection = "Data Source=58.211.23.172;Initial Catalog=WuAnDBPrd2;Password=mk2XA5+#;User ID=sa;";
        public SugarDbContext()
        {
            Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = Connection,
                DbType = DbType.SqlServer,
                InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
                IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了

            });
            //调式代码 用来打印SQL 
            Db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql + "\r\n" +
                    Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Console.WriteLine();
            };

        }
        //注意:不能写成静态的
        public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作
    }
}
View Code

需要引入Sugar和Json 两个包

 然后,我们封装sqlSuagr的一些常用方法,如下:

using appDataInterface;
using appModel;
using AppSugarContext;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace appDataService
{
    public class DataRepository
    {
        public static SugarDbContext sugar = new SugarDbContext();
        public static string NewGuid()
        {
            return Guid.NewGuid().ToString("N");
        }
        /// <summary>
        /// 获取返回的列表
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <param name="sql"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        public static List<U> GetListBySql<U>(string sql, string orderby = "")
            where U : class, new()
        {
            List<U> result = null;
            using (var db = sugar.Db)
            {
                if (string.IsNullOrEmpty(orderby))
                {
                    result = db.SqlQueryable<U>(sql).ToList();
                }
                else
                {
                    result = db.SqlQueryable<U>(sql).OrderBy(orderby).ToList();
                }
            }
            return result;
        }
        /// <summary>
        /// 获取返回的列表-参数化
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <param name="sql"></param>
        /// <param name="where"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static List<U> GetListBySql<U>(string sql, string where, object parameters)
            where U : class, new()
        {
            List<U> result = null;
            using (var db = sugar.Db)
            {
                result = db.SqlQueryable<U>(sql).Where(where, parameters).ToList();
            }
            return result;
        }

        /// <summary>
        /// 获取DbSet 第一行
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static U GetOneBySql<U>(string sql)
            where U : class, new()
        {
            U result = null;
            using (var db = sugar.Db)
            {
                result = db.SqlQueryable<U>(sql).First();
            }
            return result;
        }
        /// <summary>
        /// 获取第一行第一列的值 并转化为Int
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int GetInt(string sql)
        {
            using (var db = sugar.Db)
            {
                return db.Ado.GetInt(sql);
            }
        }
        /// <summary>
        /// 获取第一行第一列的值 并转化为Double
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static double GetDouble(string sql)
        {
            using (var db = sugar.Db)
            {
                return db.Ado.GetDouble(sql);
            }
        }
        /// <summary>
        /// SQL 分页
        /// </summary>
        /// <typeparam name="E">返回值对象</typeparam>
        /// <typeparam name="U">查询类,继承自PaginationModel</typeparam>
        /// <param name="sql">sql</param>
        /// <param name="OrderBy">排序</param>
        /// <param name="u">查询对象,继承自PaginationModel</param>
        /// <returns></returns>
        public static PaginationListModel<E> PageQuery<E, U>(string sql, string OrderBy, U u)
            where U : PaginationModel
            where E : class, new()
        {
            var db = sugar.Db;
            int total = 0;
            List<E> list = null;
            if (string.IsNullOrEmpty(OrderBy))
            {
                list = db.SqlQueryable<E>(sql).ToPageList(u.pageNumber, u.pageSize, ref total);
            }
            else
            {
                list = db.SqlQueryable<E>(sql).OrderBy(OrderBy).ToPageList(u.pageNumber, u.pageSize, ref total);
            }
            return new PaginationListModel<E>()
            {
                data = list,
                pagination = new BasePaginationModel()
                {
                    pageNumber = u.pageNumber,
                    pageSize = u.pageSize,
                    total = total
                }
            };
        }
        /// <summary>
        ///  SQL 分页 参数化
        /// </summary>
        /// <typeparam name="E"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="sql"></param>
        /// <param name="OrderBy"></param>
        /// <param name="u"></param>
        /// <param name="where"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static PaginationListModel<E> PageQuery<E, U>(string sql, string OrderBy, U u, string where, object parameters)
            where U : PaginationModel
            where E : class, new()
        {
            if (parameters == null)
            {
                return PageQuery<E, U>(sql, OrderBy, u);
            }

            var db = sugar.Db;
            int total = 0;
            List<E> list = null;
            if (string.IsNullOrEmpty(OrderBy))
            {
                list = db.SqlQueryable<E>(sql).Where(where, parameters).ToPageList(u.pageNumber, u.pageSize, ref total);
            }
            else
            {
                list = db.SqlQueryable<E>(sql).Where(where, parameters).OrderBy(OrderBy).ToPageList(u.pageNumber, u.pageSize, ref total);
            }
            return new PaginationListModel<E>()
            {
                data = list,
                pagination = new BasePaginationModel()
                {
                    pageNumber = u.pageNumber,
                    pageSize = u.pageSize,
                    total = total
                }
            };
        }
        /// <summary>
        /// 执行Sql 查询单个实体
        /// </summary>
        /// <typeparam name="E"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="sql"></param>
        /// <param name="OrderBy"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public static E PageOne<E>(string sql)
            where E : class, new()
        {
            var db = sugar.Db;
            var one = db.SqlQueryable<E>(sql).ToList().FirstOrDefault();
            return one;
        }

        /// <summary>
        /// 查询结果List的第一条记录
        /// </summary>
        /// <typeparam name="E"></typeparam>
        /// <param name="sql"></param>
        /// <param name="where"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static E PageOne<E>(string sql, string where, object parameters)
           where E : class, new()
        {
            if (parameters == null)
            {
                return PageOne<E>(sql);
            }

            var db = sugar.Db;
            var one = db.SqlQueryable<E>(sql).Where(where, parameters).ToList().FirstOrDefault();
            return one;
        }


        /// <summary>
        /// 第一行第一列
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static object ExecuteScalar(string sql, object parameters = null)
        {
            using (var db = sugar.Db)
            {
                return db.Ado.GetScalar(sql, parameters);
            }
        }

        /// <summary>
        /// 第一行第一列
        /// </summary>
        public static object ExecuteScalar(string sql)
        {
            using (var db = sugar.Db)
            {
                return db.Ado.GetScalar(sql);
            }
        }
        /// <summary>
        /// 第一行第一列    -    异步
        /// </summary>
        public static async Task<object> ExecuteScalarAsync(string sql, object parameters = null)
        {
            using (var db = sugar.Db)
            {
                return await db.Ado.GetScalarAsync(sql, parameters);
            }
        }
        /// <summary>
        /// 第一行第一列    -    异步
        /// </summary>
        public static async Task<object> ExecuteScalarAsync(string sql)
        {
            using (var db = sugar.Db)
            {
                return await db.Ado.GetScalarAsync(sql);
            }
        }
       
        public static E GetOneBySql<E>(string sql, object parameters = null)
            where E : class
        {
            using (var db = sugar.Db)
            {
                return db.Ado.SqlQuerySingle<E>(sql, parameters);
            }

        }
        /// <summary>
        /// 第一行第一列    -    异步
        /// </summary>
        public static async Task<E> GetOneBySqlAsync<E>(string sql, object parameters = null)
          where E : class
        {
            using (var db = sugar.Db)
            {
                return await db.Ado.SqlQuerySingleAsync<E>(sql, parameters);
            }

        }

        public static List<E> GetBySql<E>(string sql, object parameters = null)
            where E : class
        {
            using (var db = sugar.Db)
            {
                return db.Ado.SqlQuery<E>(sql, parameters);
            }

        }

        public static async Task<List<E>> GetBySqlAsync<E>(string sql, object parameters = null)
            where E : class
        {
            using (var db = sugar.Db)
            {
                return await db.Ado.SqlQueryAsync<E>(sql, parameters);
            }
        }
    }
}
View Code

引用:System.Data.SqlClient

调用我们封装的方法,如下:

        public GetEvseInfoModel GetEvseInfo()
        {
            string sql = string.Format(@"select *
from  A left join  B
on A.GroupID=B.uid
where   EVSENo ='{0}'", "11212174714143316"); 
            var Info = DataRepository.PageOne<GetEvseInfoModel>(sql);
            return Info;
        }

        public PaginationListModel<DeliveryCarEntitys> GetCarEntities(SearchCarParam searchaParam)
        {
            string sql = string.Format(@"SELECT
*
FROM [dbo].[DeliveryCar] d WHERE 1=1
");
            return DataRepository.PageQuery<DeliveryCarEntitys, SearchCarParam>(sql, " AddTime desc", searchaParam);
        }

        public PaginationListModel<DeliveryCarEntitys> GetCarEntities_param(SearchCarParam searchaParam)
        {
            string sql = string.Format(@"SELECT
*
FROM [dbo].[DeliveryCar] d 
");
            var where = "1=1 and FrameNo = @FrameNo";
            var para = new
            {
                FrameNo = "112" //
            };
            return DataRepository.PageQuery<DeliveryCarEntitys, SearchCarParam>(sql, "AddTime desc", searchaParam, where, para);
        }

        public async Task<int> GetCabinetCount(SearchStatistic data, CurrentUserData CurrentUser)
        {
            string sql = @"select count(1) from  A 
";
            #region 数据权限
            if (!CurrentUser.IsAdmin)
            {
                sql += " and B.SystemID=@UserSystemID";
            }
            #endregion
            if (!string.IsNullOrEmpty(data.systemId))
            {
                sql += " and B.SystemID=@SystemID";
            }
            if (data.GroupId.HasValue)
            {
                sql += " and A.GroupId=@GroupId";
            }
            if (!string.IsNullOrEmpty(data.StationStoreId))
            {
                sql += "  and (A.StationID=@StationStoreId or A.StoreId=@StationStoreId)";
            }
            var para = new
            {
                UserSystemID = CurrentUser.userLoginToken.SystemID,
                SystemID = data.systemId,
                GroupId = data.GroupId,
                StationStoreId = data.StationStoreId

            };
            var Obj = await ExecuteScalarAsync(sql, para);
            if (Obj != null)
                return Convert.ToInt32(Obj);
            return 0;

        }

        public DeliveryCarEntity GetDetail(string uid)
        {
            var sql = $@"select {GetFieldsStr("c")},s.GroupId as StoreGroupId from {nameof(DeliveryCar)} as c with(nolock) 
                        left join {nameof(SysStoreInfo)} as s with(nolock) on s.uid = c.StoreId 
                        where c.uid = @uid";
            return GetOneBySql<DeliveryCarEntity>(sql, new { uid });
        }

        public async Task<ChangeApiPageInfo> GetFirstPageBatteryInfo(CurrentWeChatUser CurrentUser)
        {
            var bol = context.Cmcustomer.Any(A => A.Uid == CurrentUser.customerId && A.HasAgreed);
            if (!bol)
            {
                return new ChangeApiPageInfo() { HasAgreed = false };
            }
            string sql = @"select * from  baty 
inner  join  mat on mat.Skuno=baty.MaterialNo
left join  cus on cus.Uid= baty.customerId
where CustomerID=@CustomerID ";
            var paras = new { CustomerID = CurrentUser.customerId };
            return await GetOneBySqlAsync<ChangeApiPageInfo>(sql, paras);
        }

        public bool HasIot(string batteryNo)
        {
            var one = PageOne<GenericObject<bool>>($@"select b.BatteryNo,
m.HasIoT
from BaseBattery b
inner join MaterialBattery m on b.MaterialNo=m.SKUNo", "BatteryNo=@BatteryNo", new { BatteryNo = batteryNo });
            return one != null && one.Value;
        }
View Code

@天才卧龙的博客

这篇关于sqlSugar 简单封装及使用案例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!