C# DbUtils操作数据库类

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using Omu.ValueInjecter;
using System.Configuration;
using Common.Data.SqlServer;


namespace Common.Data
{
    public static class DbUtils
    {
        static string cs = SqlEasy.connString; //数据库连接字符串
        public static IEnumerable GetWhere(object where) where T : new()
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;

                    cmd.CommandText = "select * from " + TableConvention.Resolve(typeof(T)) + " where "
                        .InjectFrom(new FieldsBy()
                        .SetFormat("{0}=@{0}")
                        .SetNullFormat("{0} is null")
                        .SetGlue("and"),
                        where);
                    cmd.InjectFrom(where);
                    conn.Open();

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var o = new T();
                            o.InjectFrom(dr);
                            yield return o;
                        }
                    }
                }
            }
        }

        public static int CountWhere(object where) where T : new()
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "select count(*) from " + TableConvention.Resolve(typeof(T)) + " where "
                        .InjectFrom(new FieldsBy()
                        .SetFormat("{0}=@{0}")
                        .SetNullFormat("{0} is null")
                        .SetGlue("and"),
                        where);
                    cmd.InjectFrom(where);
                    conn.Open();

                    return (int)cmd.ExecuteScalar();
                }
            }
        }

        public static int Delete(int id)
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "delete from " + TableConvention.Resolve(typeof(T)) + " where KeyID=@KeyID";

                cmd.InjectFrom(new { KeyID = id });
                conn.Open();
                return cmd.ExecuteNonQuery();
            }
        }

        public static int Delete(string ids)
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "delete from " + TableConvention.Resolve(typeof(T)) + " where charindex(',' + cast(keyid AS varchar(50)) + ',',','  + @KeyID + ',') > 0";

                cmd.InjectFrom(new { KeyID = ids });
                conn.Open();
                return cmd.ExecuteNonQuery();
            }
        }

        /// the id of the inserted object 
        public static int Insert(object o)
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                o.ToString();
                cmd.CommandText = "insert " + TableConvention.Resolve(o) + " ("
                    .InjectFrom(new FieldsBy().IgnoreFields("keyid"), o) + ") values("
                    .InjectFrom(new FieldsBy().IgnoreFields("keyid").SetFormat("@{0}"), o)
                    + ") select @@identity";

                cmd.InjectFrom(new SetParamsValues().IgnoreFields("keyid"), o);

                conn.Open();
                object obj = cmd.ExecuteScalar();
                return Convert.ToInt32(obj);
            }
        }

        #region 添加数据并且返回guid
        /// 
        /// 添加数据并且返回guid
        /// 
        /// 数据
        /// 列名称
        /// 
        public static Boolean InsertGuid(object o, string name, out string err)
        {
            var conn = new SqlConnection(cs);
            var cmd = conn.CreateCommand();
            Boolean IsTrue = false;
            err = "";
            try
            {
                cmd.CommandType = CommandType.Text;
                o.ToString();
                cmd.CommandText = "insert " + TableConvention.Resolve(o) + " ("
                    .InjectFrom(new FieldsBy().IgnoreFields(name), o) + ") values("
                    .InjectFrom(new FieldsBy().IgnoreFields(name).SetFormat("@{0}"), o)
                    + ") select @@identity";
                cmd.InjectFrom(new SetParamsValues().IgnoreFields(name), o);
                conn.Open();
                object obj = cmd.ExecuteScalar();
                if (o != null)
                {
                    IsTrue = true;
                }
            }
            catch (Exception ex)
            {
                IsTrue = false;
                err = ex.Message;
            }
            return IsTrue;
        }
        #endregion

        public static int Update(object o)
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "update " + TableConvention.Resolve(o) + " set "
                    .InjectFrom(new FieldsBy().IgnoreFields("keyid").SetFormat("{0}=@{0}"), o)
                    + " where KeyID = @KeyID";

                cmd.InjectFrom(o);

                conn.Open();
                return Convert.ToInt32(cmd.ExecuteNonQuery());
            }
        }

        #region
        /// 
        /// 根据guid修改数据
        /// 
        /// 数据
        /// 主键列名称
        /// 错误信息
        /// 
        public static Boolean UpdateGuid(object o, string name, out string err)
        {
            var conn = new SqlConnection(cs);
            var cmd = conn.CreateCommand();
            Boolean IsTrue = false;
            err = "";
            try
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "update " + TableConvention.Resolve(o) + " set "
                    .InjectFrom(new FieldsBy().IgnoreFields(name).SetFormat("{0}=@{0}"), o)
                    + " where" + " " + name + "=" + "@" + name;
                cmd.InjectFrom(o);
                conn.Open();
                object obj = cmd.ExecuteScalar();
                if (o != null)
                {
                    IsTrue = true;
                }
            }
            catch (Exception ex)
            {
                IsTrue = false;
                err = ex.Message;
            }
            return IsTrue;
        }
        #endregion

        public static int Update(object o, params string[] fields)
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "update " + TableConvention.Resolve(o) + " set "
                    .InjectFrom(new FieldsBy().IgnoreFields(fields).SetFormat("{0}=@{0}"), o)
                    + " where KeyID = @KeyID";

                cmd.InjectFrom(o);

                conn.Open();
                return Convert.ToInt32(cmd.ExecuteNonQuery());
            }
        }

        public static int UpdateWhatWhere(object what, object where)
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "update " + TableConvention.Resolve(typeof(T)) + " set "
                    .InjectFrom(new FieldsBy().SetFormat("{0}=@{0}"), what)
                    + " where "
                    .InjectFrom(new FieldsBy()
                    .SetFormat("{0}=@wp{0}")
                    .SetNullFormat("{0} is null")
                    .SetGlue("and"),
                    where);

                cmd.InjectFrom(what);
                cmd.InjectFrom(new SetParamsValues().Prefix("wp"), where);

                conn.Open();
                return cmd.ExecuteNonQuery();
            }
        }


        public static int InsertNoIdentity(object o)
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "insert " + TableConvention.Resolve(o) + " ("
                    .InjectFrom(new FieldsBy().IgnoreFields("keyid"), o) + ") values("
                    .InjectFrom(new FieldsBy().IgnoreFields("keyid").SetFormat("@{0}"), o) + ")";

                cmd.InjectFrom(o);

                conn.Open();
                return cmd.ExecuteNonQuery();
            }
        }

        /// rows affected
        public static int ExecuteNonQuerySp(string sp, object parameters)
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = sp;
                    cmd.InjectFrom(parameters);
                    conn.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        public static int ExecuteNonQuery(string commendText, object parameters)
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = commendText;
                    cmd.InjectFrom(parameters);
                    conn.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        public static IEnumerable ExecuteReader(string sql, object parameters) where T : new()
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = sql;
                    cmd.InjectFrom(parameters);
                    conn.Open();
                    using (var dr = cmd.ExecuteReader())
                        while (dr.Read())
                        {
                            var o = new T();
                            o.InjectFrom(dr);
                            yield return o;
                        }
                }
            }
        }


        public static IEnumerable ExecuteReaderSp(string sp, object parameters) where T : new()
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = sp;
                    cmd.InjectFrom(parameters);
                    conn.Open();
                    using (var dr = cmd.ExecuteReader())
                        while (dr.Read())
                        {
                            var o = new T();
                            o.InjectFrom(dr);
                            yield return o;
                        }
                }
            }
        }

        public static IEnumerable ExecuteReaderSpValueType(string sp, object parameters)
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = sp;
                    cmd.InjectFrom(parameters);
                    conn.Open();
                    using (var dr = cmd.ExecuteReader())
                        while (dr.Read())
                        {
                            yield return (T)dr.GetValue(0);
                        }
                }
            }
        }

        public static int Count()
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "select count(*) from " + TableConvention.Resolve(typeof(T));
                    conn.Open();

                    return (int)cmd.ExecuteScalar();
                }
            }
        }

        public static int GetPageCount(int pageSize, int count)
        {
            var pages = count / pageSize;
            if (count % pageSize > 0) pages++;
            return pages;
        }

        public static IEnumerable GetAll() where T : new()
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "select * from " + TableConvention.Resolve(typeof(T));
                    conn.Open();

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var o = new T();
                            o.InjectFrom(dr);
                            yield return o;
                        }
                    }
                }
            }
        }

        public static IEnumerable GetList(string sql, object parameters) where T : new()
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = sql;
                    cmd.InjectFrom(parameters);
                    conn.Open();

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var o = new T();
                            o.InjectFrom(dr);
                            yield return o;
                        }
                    }
                }
            }
        }

        public static DataTable GetPageWithSp(ProcCustomPage pcp, out int recordCount)
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = pcp.Sp_PagerName;
                    cmd.InjectFrom(new SetParamsValues().IgnoreFields("sp_pagername"), pcp);

                    SqlParameter outputPara = new SqlParameter("@RecordCount", SqlDbType.Int);
                    outputPara.Direction = ParameterDirection.Output;
                    cmd.Parameters.Add(outputPara);

                    conn.Open();

                    using (var da = new SqlDataAdapter(cmd))
                    {
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        cmd.Parameters.Clear();
                        recordCount = PublicMethod.GetInt(outputPara.Value);
                        conn.Close();
                        return ds.Tables[0];
                    }
                }
            }
        }

        public static void GetCountWhere(ProcCustomPage pcp, out int recordCount)
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlParameter outputPara = new SqlParameter("@RecordCount", SqlDbType.Int);
                    outputPara.Direction = ParameterDirection.Output;
                    cmd.Parameters.Add(outputPara);

                    conn.Open();

                    using (var da = new SqlDataAdapter(cmd))
                    {
                        cmd.Parameters.Clear();
                        recordCount = PublicMethod.GetInt(outputPara.Value);
                        conn.Close();
                    }
                }
            }
        }

        public static IEnumerable GetPage(int page, int pageSize) where T : new()
        {
            using (var conn = new SqlConnection(cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    var name = TableConvention.Resolve(typeof(T));

                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = string.Format(@"with result as(select *, ROW_NUMBER() over(order by keyid desc) nr
                            from {0}
                    )
                    select  * 
                    from    result
                    where   nr  between (({1} - 1) * {2} + 1)
                            and ({1} * {2}) ", name, page, pageSize);
                    conn.Open();

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var o = new T();
                            o.InjectFrom(dr);
                            yield return o;
                        }
                    }
                }
            }
        }

        public static T Get(long keyid) where T : new()
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from " + TableConvention.Resolve(typeof(T)) + " where keyid = " + keyid;
                conn.Open();

                using (var dr = cmd.ExecuteReader())
                    while (dr.Read())
                    {
                        var o = new T();
                        o.InjectFrom(dr);
                        return o;
                    }
            }
            return default(T);
        }

        #region
        /// 
        /// 根据guid获取数据
        /// 
        /// 表名
        /// 主键id
        /// 需要改的主键列
        /// 
        public static T GetGuid(string keyid, string name) where T : new()
        {
            using (var conn = new SqlConnection(cs))
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from " + TableConvention.Resolve(typeof(T)) + " where " + name + "=" + "'" + keyid + "'";
                conn.Open();

                using (var dr = cmd.ExecuteReader())
                    while (dr.Read())
                    {
                        var o = new T();
                        o.InjectFrom(dr);
                        return o;
                    }
            }
            return default(T);
        }
        #endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.Data
{
    public class ProcCustomPage
    {


        public ProcCustomPage() 
        {
            ShowFields = "*";
            KeyFields = "keyid";
            OrderFields = "keyid desc";
            PageIndex = 1;
            PageSize = 20;
            WhereString = "";
            Sp_PagerName = "ProcCustomPage";
        }

        public string Sp_PagerName
        {
            get;
            set;
        }

        public ProcCustomPage(string tablename) :this()
        {
            TableName = tablename;
        }
        
        /// 
        /// 表名或视图名称
        /// 
        public string TableName { get; set; }

        /// 
        /// 查询字段
        /// 
        public string ShowFields { get; set; }

        /// 
        /// 主键或标识字段
        /// 
        public string KeyFields { get; set; }

        /// 
        /// 排序字段 如:keyid desc,name asc
        /// 
        public string OrderFields { get; set; }

        /// 
        /// 页码
        /// 
        public int PageIndex { get; set; }

        /// 
        /// 每页记录数
        /// 
        public int PageSize { get; set; }

        /// 
        /// 查询条件
        /// 
        public string WhereString { get; set; }
    }
}

ProcCustomPage类:


TableConvention类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.Data
{
    public static class TableConvention
    {

        public static string Resolve(Type t)
        {
            string _tablename = "";
            TableNameAttribute tableName;
            var name = t.Name;
            foreach(Attribute  attr in t.GetCustomAttributes(true))
            {
                tableName = attr as TableNameAttribute;
                if(tableName!=null)
                    _tablename = tableName.Name;
            }

            if (string.IsNullOrEmpty(_tablename))
            {
                if (name.EndsWith("s"))
                    _tablename = t.Name + "es";
                _tablename = t.Name + "s";
            }

            return _tablename;
        }

        public static string Resolve(object o)
        {
            return Resolve(o.GetType());
        }
    }
}




你可能感兴趣的:(C#,SQL,Serve,C#)