數據庫操作封裝的突然想法

使用Action和Function做參數封裝數據庫操作,可以在一個連接中進行多個操作,使用起來比較方便

封裝的方法:

 /// <summary>
        /// 執行sql
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="para"></param>
        public static void Execute(Action<IDbConnection> func)
        {
            using(IDbConnection conn = util.DB.CreateConnection())
            {
                func(conn);
            }
        }

        /// <summary>
        /// 執行sql,並返回結果
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        public static T ExecuteResult<T>(Func<IDbConnection,T> func)
        {
            using (IDbConnection conn = util.DB.CreateConnection())
            {
                T obj = func(conn);
                return obj;
            }
        }

只執行sql,插入行政規劃記錄

 public static void add(Xzqh xzqh)
        {
            Dal.Common.Execute((IDbConnection conn) =>
            {
                conn.Execute("insert into t_code_xzqh(code,name,parentcode) values(@code,@name,@parentcode)", xzqh);
            });
        }

獲取行政規劃樹:

 public static IEnumerable<Xzqh> listTree()
        {
            var robj = Dal.Common.ExecuteResult((IDbConnection conn) =>
            {
                var query = conn.Query<Xzqh>("select * from t_code_xzqh where parentcode is null order by code");
                List<Xzqh> list = new List<Xzqh>();
                foreach (var item in query)
                {
                    var q = getChildren(conn, item);
                    list.Add(q);
                }
                return list;
            });
            return robj;
        }


        private static Xzqh getChildren(IDbConnection conn, Xzqh parent)
        {
            if (parent.children == null)
            {
                parent.children = conn.Query<Xzqh>("select * from t_code_xzqh where parentcode=@code order by code", new { code = parent.code }).ToList();
            }
            foreach (var c in parent.children)
            {
                if (conn.ExecuteScalar<int>("select count(0) from t_code_xzqh where parentcode=@code", new { code = c.code }) > 0)
                {
                    getChildren(conn, c);
                }
            }
            return parent;
        }

注:數據庫操作使用的是Dapper類庫

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章