C#面向对象的数据库 *** 作类DbHelper

C#面向对象的数据库 *** 作类DbHelper,第1张

概述C#面向对象的数据库 *** 作类DbHelper

下面是内存溢出 jb51.cc 通过网络收集整理的代码片段。

内存溢出小编现在分享给大家,也给大家做个参考。

 using System;using System.Configuration;using System.Collections.Generic;using System.Data;using System.Data.Common;using System.Text;  public static class Db{    private static ConnectionStringSettings ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"];    public static DbProvIDerFactory Factory = DbProvIDerFactorIEs.GetFactory(ConnectionString.ProvIDername);      public static DbConnection CreateConnection()    {        DbConnection con = Factory.CreateConnection();        con.ConnectionString = ConnectionString.ConnectionString;        return con;    }      #region 参数      public static DbParameter CreateParameter(DbParameter param)    {        return CreateParameter(param.Parametername,param.Value,param.DbType,param.Size,param.Direction,param.sourceColumn,param.sourceColumnNullMapPing,param.sourceVersion);    }      public static DbParameter CreateParameter(string Parametername,object Value,DbType? DbType = null,int? Size = null,ParameterDirection? Direction = null,string SourceColumn = null,bool? SourceColumnNullMapPing = null,DaTarowVersion? SourceVersion = null)    {        DbParameter param = Factory.CreateParameter();          param.Parametername = Parametername;        param.Value = Value;          if (DbType != null)            param.DbType = DbType.Value;        if (Size != null)            param.Size = Size.Value;        if (Direction != null)            param.Direction = Direction.Value;        if (SourceColumn != null)            param.sourceColumn = SourceColumn;        if (SourceColumnNullMapPing != null)            param.sourceColumnNullMapPing = SourceColumnNullMapPing.Value;        if (SourceVersion != null)            param.sourceVersion = SourceVersion.Value;          return param;    }      private static DbParameter[] ConvertParameters(object[] parameters)    {        List<DbParameter> paramList = new List<DbParameter>();          for (int i = 0; i < parameters.Length; i++)        {            if (parameters[i] is DbParameterCollection)                foreach (DbParameter item in parameters[i] as DbParameterCollection) paramList.Add(CreateParameter(item));            else if (parameters[i] is DbParameter)                paramList.Add(parameters[i] as DbParameter);            else                paramList.Add(CreateParameter("@" + i,parameters[i]));        }          return paramList.ToArray();    }      #endregion      public static query query(string query,params object[] parameters)    {        return new query(query,ConvertParameters(parameters));    }      public static bool Insert(string table,object model)    {        StringBuilder fIElds = new StringBuilder();        StringBuilder values = new StringBuilder();        List<DbParameter> paramList = new List<DbParameter>();          foreach (var item in model.GetType().GetPropertIEs())        {            fIElds.AppendFormat("[{0}],",item.name);            values.AppendFormat("@{0},item.name);            paramList.Add(CreateParameter("@" + item.name,item.GetValue(model,null)));        }          return Db.query(string.Format("insert into [{0}]({1}) values({2})",table,fIElds.ToString().TrimEnd(','),values.ToString().TrimEnd(',')),paramList.ToArray()).Execute() > 0;    }      public static bool Update(string table,object model,string where,params object[] parameters)    {        StringBuilder fIEldsAndValues = new StringBuilder();        List<DbParameter> paramList = new List<DbParameter>();          foreach (var item in model.GetType().GetPropertIEs())        {            fIEldsAndValues.AppendFormat("[{0}][email protected]{0},null)));        }          paramList.AddRange(ConvertParameters(parameters));          return Db.query(string.Format("update [{0}] set {1}",fIEldsAndValues.ToString().TrimEnd(',') + ((where ?? "").Trim() == "" ? "" : " where " + where)),paramList.ToArray()).Execute() > 0;    }}  public class query{    #region 构造方法      public query(string query,DbParameter[] parameters)    {        sqlquery = query;        Parameters = parameters;    }      public query(string query,DbParameter[] parameters,bool isException)        : this(query,parameters)    {        IsException = isException;    }      #endregion      #region 属性/字段      private bool IsException { get; set; }    public string sqlquery { get; set; }    public DbParameter[] Parameters { get; set; }      #endregion      #region 执行基础      private T ExecuteCommon<T>(Func<DbCommand,T> function)    {        using (DbConnection con = Db.CreateConnection())        using (DbCommand cmd = con.CreateCommand())        {            cmd.CommandText = sqlquery;            cmd.Parameters.AddRange(Parameters);            con.open();            T result = function(cmd);            cmd.Parameters.Clear();            return result;        }    }      public T Execute<T>(Func<DbCommand,T> function,T exValue = default(T))    {        if (IsException)            return ExecuteCommon<T>(function);          try        {            return ExecuteCommon<T>(function);        }        catch (Exception e)        {            Console.Writeline(e.ToString());            return exValue;        }    }      public voID Execute(Action<DbCommand> action)    {        Execute(cmd => { action(cmd); return 0; });    }      #endregion      #region 执行查询      public int Execute()    {        return Execute(cmd => cmd.ExecuteNonquery());    }      public object Scalar()    {        return Execute(cmd => cmd.ExecuteScalar());    }      public T Scalar<T>()    {        return Execute(cmd => (T)cmd.ExecuteScalar());    }      public query top(int count)    {        return Db.query(string.Format("select top {0} * from ({1}) as t0",count,sqlquery),Parameters);    }      public Single ToSingle()    {        return Execute(cmd =>        {            Single s = new Single();              using (var dr = cmd.ExecuteReader())            {                if (dr.Read())                {                    string name = string.Empty;                      for (int i = 0; i < dr.FIEldCount; i++)                    {                        name = dr.Getname(i);                        s[name] = dr[name];                    }                }                else                {                    throw new Exception("Not Find !!");                }            }              return s;        });      }      public Datatable ToDatatable()    {        return Execute(cmd =>        {            DbDataAdapter da = Db.Factory.CreateDataAdapter();            da.SelectCommand = cmd;            Datatable dt = new Datatable();            da.Fill(dt);            return dt;        });    }      public List<T> ToList<T>()    {        return Execute(cmd =>        {            List<T> List = new List<T>();              using (var dr = cmd.ExecuteReader())            {                while (dr.Read())                {                    Type t = typeof(T);                    T s = default(T);                    string name = string.Empty;                      for (int i = 0; i < dr.FIEldCount; i++)                    {                        name = dr.Getname(i);                        var pro = t.GetProperty(name);                          if (pro != null)                            pro.SetValue(s,dr[name],null);                    }                      List.Add(s);                }            }              return List;        },new List<T>());    }      public overrIDe string ToString()    {        return Scalar<string>();    }      #endregion      #region 分页      private query RecordCountquery    {        get { return Db.query(string.Format("select count(*) from ({0}) as t0",Parameters); }    }      private query PagerResultquery(string primaryKey,int pageIndex,int pageSize)    {        return Db.query(string.Format("select top {1} * from ({0}) as t0" +            (pageIndex > 1 ? " where t0.{3} not in (select top {2} t1.{3} from ({0}) as t1)" : ""),sqlquery,pageSize,pageIndex * pageSize,primaryKey),Parameters);    }      public Datatable topager(string primaryKey,int pageSize,Action<int> recordCount)    {        recordCount(RecordCountquery.Scalar<int>());        return PagerResultquery(primaryKey,pageIndex,pageSize).ToDatatable();    }      public Datatable topager(int pageIndex,Action<int> recordCount)    {        return topager("ID",recordCount);    }      public List<T> topager<T>(string primaryKey,pageSize).ToList<T>();    }      public List<T> topager<T>(int pageIndex,Action<int> recordCount)    {        return topager<T>("ID",recordCount);    }      #endregion}  public class Single : Dictionary<string,object>{    public new object this[string name]    {        get { return base[name.Tolower()]; }        set { Add(name.Tolower(),value); }    }}

以上是内存溢出(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

总结

以上是内存溢出为你收集整理的C#面向对象的数据库 *** 作类DbHelper全部内容,希望文章能够帮你解决C#面向对象的数据库 *** 作类DbHelper所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1238171.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存