2023年6月21日发(作者:)

c#mysql封装类_C#.NET更智能的数据库操作的封装完整版(重构)前述:第⼀次发表⽂章,不过是对数据库简单的封装,主要是阐述下思路。那么在上篇⽂章,在⼤家的指导下和提出意见,并⾃⼰对代码进⾏了思考。在这两天我重构了新的框架,我觉得我写的可以称得上框架,为什么?请⼤家往下看。不过在项⽬中没有很多注释。笔者除了课余学习时候,⼤部分时间在完成学校的功课,没有许多时间,所以也就偷下懒,请⼤家体谅。这次框架分为⼏个部分:拼接数据库语句、数据库执⾏、数据库连接控制、异常类、⽤户使⽤的DbHelper。等下我回⽤⽂字和图还分析这个部分。经过重构后,类增多了,⽽且能够极⼤的⽀持开闭原则,我应该说就是与实际数据库⽆关,⽽且在上层使⽤中,不需要在引⽤ent这样实际访问的东西。虽然笔者只写了sql server的实例,但是如果扩展其他的数据库,也⽆需⼤规模的修改旧的代码,并且使⽤参数,能够防⽌注⼊攻击,⽀持事务。好,先看怎么使⽤框架。DbHelper helper = newDbHelper();Connection("MyConnection","Data Source=CN-20161106HMJI;Initial Catalog=ShopInfo;IntegratedSecurity=True",);PlaceInfo model= String(o => ("PlaceInfo").Select().AndWhere("SAddNo", 1)).ToModel();();上⾯是使⽤的⼀个例⼦,创建连接字符串,然后查询获取实例,已经没有打开数据库,或者是command的语句,使⽤起来是否⼗分简单,上⾯这句运⾏没有问题的,因为框架灵活度太⼤,测试的话不能所有都包含,这也是没办法,接下来跟着⽂章,⼀步步分析。上次说,链式编程很好⽤,所以这次同样是链式编程,但这次更为强⼤。⼤家知道,dal的链式编程,主要是得到数据,⽽得到数据⽆⾮是对数据库查询语⾔进⾏封装。所以,在框架上,我封装了⼀个拼接语句的类,⾥⾯包含了我认为⽐较常⽤的数据库语句,⽀持order by。还有最强⼤的是,能够⽀持嵌套查询!也就是封装的sql语句可以是select * from tableName where Id in(select id from tablename where ...)...这样⼦的。使⽤起来⼗分的⽅便。⽽且还有排序orderby,等,可以在使⽤这套框架封装更使⽤的⽅法。第⼆个新增的是连接控制,这个是这套框架的关键,因为框架不能占⽤内存,所以⽆论在拼接查询语句,还是在执⾏部分,都没有对数据库创建的语句,⽽是采⽤注⼊式,通过连接控制类,创建好数据库连接后,注⼊到所需要的部分中。⽽且这⾥控制了最耗性能的反射,对模型中的属性进⾏反射,都是耗时间,所以这⾥设置了缓存,对已经创建过对象的保存在这⾥,在拼接数据库语句或者是执⾏阶段需要⽤到,注⼊到其中,就可以省下时间。第三个增加的是异常类,不过我封装的⽐较简单,⾥⾯就⼀个可重载的⽅法,这个是⽤来发⽣异常时候,⽤户能够⾃⼰设置发⽣错误之后应该做什么(⽐如保存到⽇志)⽽定的。最后⼀个新增的是释放资源,因为对数据库连接,数据库连接数⽬⽐较少,但是command的数⽬在⼀般项⽬可就不是这样。可能⼤家为了⽅便,所以使⽤的时候尽情的new这样,那在我的框架设置了⼀个集合,专门存放command的,在⽤完后能够释放资源。因为考虑到在事务执⾏时候不能够对comand进⾏释放,所以在释放时候还做了判断。把有事务的command放到在事务执⾏后释放。看完上边的功能,是不是觉得⼗分强⼤,因为这个框架理解和实现起来都不容易,所以笔者尽可能的让⼤家明⽩,知道我是怎么⼀步步完成的。现在进⼊正题,先看下简单的结构图,看上去⽐较简单,不是我不会绘图,我在完成其他项⽬时候,都有完整的⽂档和图,因为现在没有太多时间,⽽且⽤软件画实在太慢了,所以⼤家将就的看吧。上图就是我框架的结构图。箭头代表关联,从下到上,代表底层到⽤户使⽤的层次。框架是⽀持对数据库的扩展,上边三个部分写继承抽象类就是如此,因为这⼏个其实就是实际数据库会使⽤到,所以使⽤⼯⼚模式,这样就能够扩展其他了。好了,看完图,就开始讲解代码。我第⼀步是从数据库拼接语句开始做的,因为这个虽然还不算底层,但是相对于其他可以独⽴,那么看下这⼀跪部分的类:usingSystem;c;;;namespaceDal{public interfaceIDbCode{//////数据库执⾏表、视图、存储过程等对象////// 名称///IDbCode From(objectObject);//////查询////// 查询的字段///IDbCode Select(string Fields = "*");//////删除//////IDbCode Delete();//////更新////// 更新对象/// 更新字段///IDbCode Update(object model,string Fields = "");//////插⼊////// 插⼊对象/// 插⼊字段///IDbCode Insert(object model,string Fields = "");//////与条件////// 条件字符串///IDbCode AndWhere(stringWhere);//////与条件////// 字段/// 值///IDbCode AndWhere(string Field,objectValue);//////与条件////// 条件字段/// 嵌套查询条件委托///IDbCode AndWhere(string Field, FuncSelect);//////与条件////// 值的类型/// 条件字段/// 值///IDbCode AndWhere(string Field,ListValues);//////或条件////// 条件字符串///IDbCode OrWhere(stringWhere);//////或条件////// 条件字段/// 值///IDbCode OrWhere(string Field, objectValue);//////或条件////// 条件字段/// 嵌套条件///IDbCode OrWhere(string Field, FuncSelect);//////或条件////// 值类型/// 条件字段/// 值///IDbCode OrWhere(string Field, ListValues);//////Top 语句/////////IDbCode Top(inttopCount);//////排序从⼩到⼤////// 排序字段///IDbCode OrderByAsc(stringField);//////排序从⼤到⼩////// 排序字段///IDbCode OrderByDesc(stringField);//////多表查询时候必须加的条件////// 在两张表中的相同字段///IDbCode ForMulTable(stringFields);stringToString();//////清空缓存//////IDbCode Clear();IDbCode CreateCode(stringsql);objectParas{get;}voidDispose();}}继承它的类:usingSystem;c;;;;e{public classSQLCode :IDbCode{stringObject;StringBuilder ExcuteString= newStringBuilder();Listparas;Dictionary>pro;static string[] s = { "select", "delect", "update", "insert"};publicSQLCode(){paras= new List();}public SQLCode(Dictionary>pro){paras= new List(); =pro;}public SQLCode(List paras, Dictionary>pro){ =paras; =pro;}public IDbCode From(objectObject){Type t=e();if(r().Equals("string")){ =ng();}else{ =;}return this;}public IDbCode Select(string Fields = "*"){if ( <= 0)return this;if (!Check(0))return this;Line("select" + Fields +"from"+ );Line("where 1 = 1");return this;}bool Check(intType){int flag = 0;string b =ng();for (int i = 0; i < ; i++)if(i!=Type)flag+= ns(s[i]) ? 1 : 0;return flag == 0;}publicIDbCode Delete(){if ( <= 0)return this;if (!Check(1))return this;Line("delete" + );Line("where 1 = 1");return this;}public IDbCode Update(object model, string Fields = ""){if ( <= 0)return this;if (!Check(2))return this;Type t=e();if ( !=Object)return this;Line("update"+ +"set");Listp;if(nsKey()){p=pro[];}else{p=perties().ToList();(, p);}string f = "";if(==0){h(o=>{f+= + "= @" +;(new SqlParameter(, ue(model, null)));});}else{string[] a = (',');h(o=>{if(ns()){f+= + "= @" + + ",";(new SqlParameter(, ue(model, null)));}});}Line(f);Line("where 1 = 1");return this;}public IDbCode Insert(object model, string Fields = ""){if ( <= 0)return this;if (!Check(3))return this;Type t=e();if ( !=Object)return this;Line("insert" + );Listp;if(nsKey()){p=pro[];}else{p=perties().ToList();(, p);}string f = "(";string f1 = "values(";if ( == 0){h(o=>{f+= +",";(new SqlParameter(, ue(model, null)));f1+= "@" + + ",";});}else{string[] a = (',');h(o=>{if(ns()){f+= + ",";(new SqlParameter(, ue(model, null)));f1+= "@" + + ",";}});}f= (dexOf(','), 1) + ")";f1= (dexOf(','), 1) + ")";Line(f);Line(f1);return this;}public IDbCode AndWhere(stringWhere){Line("and" +Where);return this;}public IDbCode AndWhere(string Field, objectValue){Line("and" + Field + "= @" +Field);(newSqlParameter(Field, Value));return this;}public IDbCode AndWhere(string Field, FuncSelect){Line("and" + Field + "in" + Select(new SQLCode(,)));return this;}public IDbCode AndWhere(string Field, ListValues){string value = "(";h(o=>{value+= o + ",";});Line("and" + Field + "in" + (dexOf(','), 1) + ")");return this;}public IDbCode OrWhere(stringWhere){Line("or" +Where);return this;}public IDbCode OrWhere(string Field, objectValue){Line("or" + Field + "= @" +Field);(newSqlParameter(Field, Value));return this;}public IDbCode OrWhere(string Field, FuncSelect){Line("or" + Field + "in" + Select(new SQLCode(,)));return this;}public IDbCode OrWhere(string Field, ListValues){string value = "(";h(o=>{value+= o + ",";});Line("or" + Field + "in" + (dexOf(','), 1) + ")");return this;}public IDbCode Top(inttopCount){if (!ng().Contains(s[0]))return this;e("select", "select top" + topCount +" ");return this;}boolCheckHasOrderBy(){return ng().Contains("order by");}public IDbCode OrderByAsc(stringField){if(CheckHasOrderBy())Line("," + Field + "asc");Line("order by" + Field+"asc");return this;}public IDbCode OrderByDesc(stringField){if(CheckHasOrderBy())Line("," + Field + "desc");Line("order by" + Field + "desc");return this;}public IDbCode ForMulTable(stringFields){List tables = (',').ToList();(',').ToList().ForEach(o =>{for (int i = 0; i < - 1; i++){Line("and" + tables[i] + "." + o + "=" + tables[i + 1] + "." +o);}});return this;}public override stringToString(){return ng();}publicIDbCode Clear(){();return this;}public IDbCode CreateCode(stringsql){Line(sql);return this;}public objectParas{get{return ;}}public voidDispose(){ = null;}}}如果有看过上次的⽂章,那么就知道这⾥部分⽅法⽤到反射,获取其中的属性来拼写语句。没什么难的,⼤家看到⾥⾯有许多的if条件,是我避免在链式组合时候,⽤户随便乱时候⽽设置的。这部分都是对字符串处理。第⼆部分是执⾏语句,这个相信⼤家写多了,先给代码:usingSystem;c;;;;e{public interfaceIDbExcute{T ToModel(IDbCode code, CommandType type =)where T : class,new();List ToList(IDbCode code,CommandType type =)where T : class,new();object ToResult(IDbCode code,CommandType type =);int ExcuteResult(IDbCode code, CommandType type =);DataTable ToDataTable(IDbCode code, CommandType type=);DataSet ToDataSet(IDbCode code, CommandTypetype=);voidOpenConnection();voidCloseConnection();void Dispose(objecttran);voidBeginTransation(stringName);voidCommit();voidRollBack();}}上⾯就是⽀持整个框架的执⾏⽅法usingSystem;c;;;;e{public classSQLExcute : IDbExcute{SqlConnection conn;Dictionary>pro;Dictionarycommand;SqlTransaction tran= null;public SQLExcute(SqlConnection conn, Dictionary>pro){ =conn; =pro;command= new Dictionary();}public List ToList(IDbCode code,CommandType type =)where T:class,new(){List list = new List();string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));Type t= typeof(T);Listpros;if(nsKey()){pros=pro[];}else{pros=perties().ToList();(, pros);}try{nnection();using (SqlDataReader reader =eReader()){while(()){T model= newT();h(o=>{if(ReaderExists(reader,)){ue(model, reader[],null);}});(model);}}}catch(Exception ex){throwex;}finally{e(name);onnection();}returnlist;}public bool ReaderExists(SqlDataReader reader, stringcolumnName){//emaTable().ter = "ColumnName= '" + columnName + "'";//return(emaTable(). > 0);return emaTable().Select("ColumnName='" + columnName + "'").Length > 0;}public void Dispose(stringname){if(nsKey(name)){SqlCommand com=command[name];(name);e();}if ( <= 0)onnection();}public void Dispose(objecttran){List list =();h(o=>{if(command[o].Transaction!=null&&command[o].Transaction==(SqlTransaction)tran){e(o);}});}public object ToResult(IDbCode code, CommandType type =){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));object result =null;try{nnection();result=eScalar();}catch(Exception ex){DoException();throwex;}finally{e(name);onnection();}returnresult;}private voidDoException(){newDbException().Done();}public int ExcuteResult(IDbCode code, CommandType type =){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));int result = 0;try{nnection();if (tran != null)ction=(SqlTransaction)tran;result=eNonQuery();}catch(Exception ex){DoException();throwex;}finally{if (tran == null)Dispose(name);onnection();}returnresult;}public ble ToDataTable(IDbCode code, CommandType type =){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));DataTable dt= newDataTable();try{using(SqlDataAdapter adapter = newSqlDataAdapter(com)){(dt);}}catch(Exception ex){DoException();throwex;}finally{Dispose(name);}returndt;}public void setCommand(SqlCommand com,Listparas){h(o=>{(o);});}public t ToDataSet(IDbCode code, CommandType type =){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));DataSet dt= newDataSet();try{using (SqlDataAdapter adapter = newSqlDataAdapter(com)){(dt);}}catch(Exception ex){DoException();throwex;}finally{Dispose(name);}returndt;}public T ToModel(IDbCode code, CommandType type =)where T : class,new(){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));Type t= typeof(T);List p = null;if(nsKey()){p=pro[];}else{p=perties().ToList();(, p);}T model= newT();try{nnection();using(SqlDataReader reader =eReader()){if(()){h(o=>{if(ReaderExists(reader,)){ue(model, reader[],null);}});}}}catch(Exception ex){DoException();throwex;}finally{Dispose(name);onnection();}returnmodel;}public voidOpenConnection(){if ( !=)();}public voidCloseConnection(){().ForEach(o=>{if (ction != null)return;});if ( !=)();}public void BeginTransation(stringName){tran=ransaction(Name);}public voidCommit(){();Dispose(tran);tran= null;}public voidRollBack(){ck();Dispose(tran);tran= null;}}}具体类中,主要设计了最重要的执⾏⽅法外,还像刚开始所述,设置了List,就是⽤来存放command对象,在执⾏完成时候时候它会⾃⼰释放。跟这个类配合使⽤的是异常类:usingSystem;c;;;namespaceDal{public classDbException{public virtual voidDone(){}}}只有短短⼏句话,这就是⽤于使⽤者想发⽣异常想它⼲什么⽽设置的。其实封装到这⾥,整个框架的⽀持已经形成,但是⽤户不能直接操作底层,⽽且还需要怎么对数据库进⾏实例,所以还要对上进⾏封装,下⼀步,往上⾛,数据库实例部分。usingSystem;c;;;namespaceDal{public interfaceIDbInstance{//////数据库名称///stringName{get;}//////获取执⾏语句类///IDbExcute Excute{get;}//////获取连接字符串///stringConnectionString{get;}//////开启事务////// 事务名称///object getTransation(stringTranName);//////获取拼写字符串类///IDbCode Code{get;}}}实现它的具体类包含所有的底层的操作,其实就是可以说是⼀个数据库实例了,创建⼀个就相当于⼀个数据库。⾥⾯将上边封装的类都在这⾥使⽤。usingSystem;c;;;;e{public classSQLInstance :IDbInstance{privateSqlConnection conn;privateIDbExcute excute;Dictionary>pro;private stringname;private stringconnectionString;private SqlTransaction tran = null;publicSQLInstance(string Name,Dictionary> pro, stringConnectionString){ =Name;tionString =ConnectionString;conn= newSqlConnection(ConnectionString); =pro;excute= newSQLExcute(conn,pro);}public stringName{get{return ;}}publicIDbExcute Excute{get{return ;}}public stringConnectionString{get{return tionString;}}public object getTransation(stringTranName){return ransaction(TranName);}publicIDbCode Code{get{return newSQLCode(pro);}}}}接下来是控制连接的类:usingSystem;c;;;tion;namespaceDal{public classDbControl{//数据库服务private static Dictionary Server = new Dictionary();//存放缓存 private static Dictionary> pro = new Dictionary>();private staticDbControl control = newDbControl();public staticDbControl getInstance(){returncontrol;}privateDbControl(){}public IDbInstance createInstance(string Name,string ConnectionString,stringtype){string nspace = typeof(IDbInstance).Namespace;Type t= e(nspace + "." +type);object obj = Instance(t, new object[] { Name, pro,ConnectionString });IDbInstance instance= obj asIDbInstance;(Name, instance);returninstance;}public IDbInstance this[stringName]{get{if(nsKey(Name))returnServer[Name];elsereturn null;}}}}这⾥算是顶层的类,最主要就是存放数据库和缓存对象。也许会好奇如果存放数据库,还可以理解,但是放着模型对象的缓存,这是为什么?因为在字符连接,还有具体执⾏数据库语句时候都会使⽤到。⽽且,不仅这个数据库,别的数据库也会使⽤到,虽然在⼀个⼤项⽬可能⽤多个数据库,但是他们使⽤到项⽬⾥的模型是⼀致的吧,因此,将缓存设置在这⾥,最好不过。⽽且整个框架只有这⼀份,其他地⽅注⼊使⽤,就不会耗内存了。最后就是⽤户使⽤的部分,这部分已经屏蔽掉许多底层的部分,只留下通⽤⽅法。这些都已经封装好了,直接在这⾥调⽤就可以。usingSystem;c;;;;namespaceDal{public classDbHelper{privateIDbInstance instance;private stringName;privateDbControl control;privateIDbCode Code;publicDbHelper(){control=tance();}public DbHelper createConnection(string Name, string ConnectionString, stringtype){ =Name;instance=Instance(Name, ConnectionString, type);return this;}public DbHelper ExcuteString(FuncFun){Code= Fun();return this;}public DbHelper createTransation(stringName){ransation(Name);return this;}publicDbHelper Rollback(){ck();return this;}publicDbHelper Commit(){();return this;}public T ToModel(CommandType Type =)where T:class,new(){if ( == null)return null;return l(,Type);}List ToList(CommandType Type =)where T:class,new(){if ( == null)return null;return (, Type);}object ToResult(CommandType Type =){if ( == null)return null;return lt(, Type);}int ExcuteResult(CommandType Type =){if ( == null)return -1;return Result(, Type);}DataTable ToDataTable(CommandType Type=){if ( == null)return null;return Table(, Type);}DataSet ToDataSet(CommandType Type=){if ( == null)return null;return Set(, Type);}}}结束:快要熄灯了,没办法在写⽂章。如果⼤家对框架有什么不明⽩,可以在下⾯评论区问我。这就是更新之后的框架,我觉得还是蛮好⽤的,虽然还没经过严密的检测。有什么问题,⼤家也可以指导下,我也在学习中~

2023年6月21日发(作者:)

c#mysql封装类_C#.NET更智能的数据库操作的封装完整版(重构)前述:第⼀次发表⽂章,不过是对数据库简单的封装,主要是阐述下思路。那么在上篇⽂章,在⼤家的指导下和提出意见,并⾃⼰对代码进⾏了思考。在这两天我重构了新的框架,我觉得我写的可以称得上框架,为什么?请⼤家往下看。不过在项⽬中没有很多注释。笔者除了课余学习时候,⼤部分时间在完成学校的功课,没有许多时间,所以也就偷下懒,请⼤家体谅。这次框架分为⼏个部分:拼接数据库语句、数据库执⾏、数据库连接控制、异常类、⽤户使⽤的DbHelper。等下我回⽤⽂字和图还分析这个部分。经过重构后,类增多了,⽽且能够极⼤的⽀持开闭原则,我应该说就是与实际数据库⽆关,⽽且在上层使⽤中,不需要在引⽤ent这样实际访问的东西。虽然笔者只写了sql server的实例,但是如果扩展其他的数据库,也⽆需⼤规模的修改旧的代码,并且使⽤参数,能够防⽌注⼊攻击,⽀持事务。好,先看怎么使⽤框架。DbHelper helper = newDbHelper();Connection("MyConnection","Data Source=CN-20161106HMJI;Initial Catalog=ShopInfo;IntegratedSecurity=True",);PlaceInfo model= String(o => ("PlaceInfo").Select().AndWhere("SAddNo", 1)).ToModel();();上⾯是使⽤的⼀个例⼦,创建连接字符串,然后查询获取实例,已经没有打开数据库,或者是command的语句,使⽤起来是否⼗分简单,上⾯这句运⾏没有问题的,因为框架灵活度太⼤,测试的话不能所有都包含,这也是没办法,接下来跟着⽂章,⼀步步分析。上次说,链式编程很好⽤,所以这次同样是链式编程,但这次更为强⼤。⼤家知道,dal的链式编程,主要是得到数据,⽽得到数据⽆⾮是对数据库查询语⾔进⾏封装。所以,在框架上,我封装了⼀个拼接语句的类,⾥⾯包含了我认为⽐较常⽤的数据库语句,⽀持order by。还有最强⼤的是,能够⽀持嵌套查询!也就是封装的sql语句可以是select * from tableName where Id in(select id from tablename where ...)...这样⼦的。使⽤起来⼗分的⽅便。⽽且还有排序orderby,等,可以在使⽤这套框架封装更使⽤的⽅法。第⼆个新增的是连接控制,这个是这套框架的关键,因为框架不能占⽤内存,所以⽆论在拼接查询语句,还是在执⾏部分,都没有对数据库创建的语句,⽽是采⽤注⼊式,通过连接控制类,创建好数据库连接后,注⼊到所需要的部分中。⽽且这⾥控制了最耗性能的反射,对模型中的属性进⾏反射,都是耗时间,所以这⾥设置了缓存,对已经创建过对象的保存在这⾥,在拼接数据库语句或者是执⾏阶段需要⽤到,注⼊到其中,就可以省下时间。第三个增加的是异常类,不过我封装的⽐较简单,⾥⾯就⼀个可重载的⽅法,这个是⽤来发⽣异常时候,⽤户能够⾃⼰设置发⽣错误之后应该做什么(⽐如保存到⽇志)⽽定的。最后⼀个新增的是释放资源,因为对数据库连接,数据库连接数⽬⽐较少,但是command的数⽬在⼀般项⽬可就不是这样。可能⼤家为了⽅便,所以使⽤的时候尽情的new这样,那在我的框架设置了⼀个集合,专门存放command的,在⽤完后能够释放资源。因为考虑到在事务执⾏时候不能够对comand进⾏释放,所以在释放时候还做了判断。把有事务的command放到在事务执⾏后释放。看完上边的功能,是不是觉得⼗分强⼤,因为这个框架理解和实现起来都不容易,所以笔者尽可能的让⼤家明⽩,知道我是怎么⼀步步完成的。现在进⼊正题,先看下简单的结构图,看上去⽐较简单,不是我不会绘图,我在完成其他项⽬时候,都有完整的⽂档和图,因为现在没有太多时间,⽽且⽤软件画实在太慢了,所以⼤家将就的看吧。上图就是我框架的结构图。箭头代表关联,从下到上,代表底层到⽤户使⽤的层次。框架是⽀持对数据库的扩展,上边三个部分写继承抽象类就是如此,因为这⼏个其实就是实际数据库会使⽤到,所以使⽤⼯⼚模式,这样就能够扩展其他了。好了,看完图,就开始讲解代码。我第⼀步是从数据库拼接语句开始做的,因为这个虽然还不算底层,但是相对于其他可以独⽴,那么看下这⼀跪部分的类:usingSystem;c;;;namespaceDal{public interfaceIDbCode{//////数据库执⾏表、视图、存储过程等对象////// 名称///IDbCode From(objectObject);//////查询////// 查询的字段///IDbCode Select(string Fields = "*");//////删除//////IDbCode Delete();//////更新////// 更新对象/// 更新字段///IDbCode Update(object model,string Fields = "");//////插⼊////// 插⼊对象/// 插⼊字段///IDbCode Insert(object model,string Fields = "");//////与条件////// 条件字符串///IDbCode AndWhere(stringWhere);//////与条件////// 字段/// 值///IDbCode AndWhere(string Field,objectValue);//////与条件////// 条件字段/// 嵌套查询条件委托///IDbCode AndWhere(string Field, FuncSelect);//////与条件////// 值的类型/// 条件字段/// 值///IDbCode AndWhere(string Field,ListValues);//////或条件////// 条件字符串///IDbCode OrWhere(stringWhere);//////或条件////// 条件字段/// 值///IDbCode OrWhere(string Field, objectValue);//////或条件////// 条件字段/// 嵌套条件///IDbCode OrWhere(string Field, FuncSelect);//////或条件////// 值类型/// 条件字段/// 值///IDbCode OrWhere(string Field, ListValues);//////Top 语句/////////IDbCode Top(inttopCount);//////排序从⼩到⼤////// 排序字段///IDbCode OrderByAsc(stringField);//////排序从⼤到⼩////// 排序字段///IDbCode OrderByDesc(stringField);//////多表查询时候必须加的条件////// 在两张表中的相同字段///IDbCode ForMulTable(stringFields);stringToString();//////清空缓存//////IDbCode Clear();IDbCode CreateCode(stringsql);objectParas{get;}voidDispose();}}继承它的类:usingSystem;c;;;;e{public classSQLCode :IDbCode{stringObject;StringBuilder ExcuteString= newStringBuilder();Listparas;Dictionary>pro;static string[] s = { "select", "delect", "update", "insert"};publicSQLCode(){paras= new List();}public SQLCode(Dictionary>pro){paras= new List(); =pro;}public SQLCode(List paras, Dictionary>pro){ =paras; =pro;}public IDbCode From(objectObject){Type t=e();if(r().Equals("string")){ =ng();}else{ =;}return this;}public IDbCode Select(string Fields = "*"){if ( <= 0)return this;if (!Check(0))return this;Line("select" + Fields +"from"+ );Line("where 1 = 1");return this;}bool Check(intType){int flag = 0;string b =ng();for (int i = 0; i < ; i++)if(i!=Type)flag+= ns(s[i]) ? 1 : 0;return flag == 0;}publicIDbCode Delete(){if ( <= 0)return this;if (!Check(1))return this;Line("delete" + );Line("where 1 = 1");return this;}public IDbCode Update(object model, string Fields = ""){if ( <= 0)return this;if (!Check(2))return this;Type t=e();if ( !=Object)return this;Line("update"+ +"set");Listp;if(nsKey()){p=pro[];}else{p=perties().ToList();(, p);}string f = "";if(==0){h(o=>{f+= + "= @" +;(new SqlParameter(, ue(model, null)));});}else{string[] a = (',');h(o=>{if(ns()){f+= + "= @" + + ",";(new SqlParameter(, ue(model, null)));}});}Line(f);Line("where 1 = 1");return this;}public IDbCode Insert(object model, string Fields = ""){if ( <= 0)return this;if (!Check(3))return this;Type t=e();if ( !=Object)return this;Line("insert" + );Listp;if(nsKey()){p=pro[];}else{p=perties().ToList();(, p);}string f = "(";string f1 = "values(";if ( == 0){h(o=>{f+= +",";(new SqlParameter(, ue(model, null)));f1+= "@" + + ",";});}else{string[] a = (',');h(o=>{if(ns()){f+= + ",";(new SqlParameter(, ue(model, null)));f1+= "@" + + ",";}});}f= (dexOf(','), 1) + ")";f1= (dexOf(','), 1) + ")";Line(f);Line(f1);return this;}public IDbCode AndWhere(stringWhere){Line("and" +Where);return this;}public IDbCode AndWhere(string Field, objectValue){Line("and" + Field + "= @" +Field);(newSqlParameter(Field, Value));return this;}public IDbCode AndWhere(string Field, FuncSelect){Line("and" + Field + "in" + Select(new SQLCode(,)));return this;}public IDbCode AndWhere(string Field, ListValues){string value = "(";h(o=>{value+= o + ",";});Line("and" + Field + "in" + (dexOf(','), 1) + ")");return this;}public IDbCode OrWhere(stringWhere){Line("or" +Where);return this;}public IDbCode OrWhere(string Field, objectValue){Line("or" + Field + "= @" +Field);(newSqlParameter(Field, Value));return this;}public IDbCode OrWhere(string Field, FuncSelect){Line("or" + Field + "in" + Select(new SQLCode(,)));return this;}public IDbCode OrWhere(string Field, ListValues){string value = "(";h(o=>{value+= o + ",";});Line("or" + Field + "in" + (dexOf(','), 1) + ")");return this;}public IDbCode Top(inttopCount){if (!ng().Contains(s[0]))return this;e("select", "select top" + topCount +" ");return this;}boolCheckHasOrderBy(){return ng().Contains("order by");}public IDbCode OrderByAsc(stringField){if(CheckHasOrderBy())Line("," + Field + "asc");Line("order by" + Field+"asc");return this;}public IDbCode OrderByDesc(stringField){if(CheckHasOrderBy())Line("," + Field + "desc");Line("order by" + Field + "desc");return this;}public IDbCode ForMulTable(stringFields){List tables = (',').ToList();(',').ToList().ForEach(o =>{for (int i = 0; i < - 1; i++){Line("and" + tables[i] + "." + o + "=" + tables[i + 1] + "." +o);}});return this;}public override stringToString(){return ng();}publicIDbCode Clear(){();return this;}public IDbCode CreateCode(stringsql){Line(sql);return this;}public objectParas{get{return ;}}public voidDispose(){ = null;}}}如果有看过上次的⽂章,那么就知道这⾥部分⽅法⽤到反射,获取其中的属性来拼写语句。没什么难的,⼤家看到⾥⾯有许多的if条件,是我避免在链式组合时候,⽤户随便乱时候⽽设置的。这部分都是对字符串处理。第⼆部分是执⾏语句,这个相信⼤家写多了,先给代码:usingSystem;c;;;;e{public interfaceIDbExcute{T ToModel(IDbCode code, CommandType type =)where T : class,new();List ToList(IDbCode code,CommandType type =)where T : class,new();object ToResult(IDbCode code,CommandType type =);int ExcuteResult(IDbCode code, CommandType type =);DataTable ToDataTable(IDbCode code, CommandType type=);DataSet ToDataSet(IDbCode code, CommandTypetype=);voidOpenConnection();voidCloseConnection();void Dispose(objecttran);voidBeginTransation(stringName);voidCommit();voidRollBack();}}上⾯就是⽀持整个框架的执⾏⽅法usingSystem;c;;;;e{public classSQLExcute : IDbExcute{SqlConnection conn;Dictionary>pro;Dictionarycommand;SqlTransaction tran= null;public SQLExcute(SqlConnection conn, Dictionary>pro){ =conn; =pro;command= new Dictionary();}public List ToList(IDbCode code,CommandType type =)where T:class,new(){List list = new List();string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));Type t= typeof(T);Listpros;if(nsKey()){pros=pro[];}else{pros=perties().ToList();(, pros);}try{nnection();using (SqlDataReader reader =eReader()){while(()){T model= newT();h(o=>{if(ReaderExists(reader,)){ue(model, reader[],null);}});(model);}}}catch(Exception ex){throwex;}finally{e(name);onnection();}returnlist;}public bool ReaderExists(SqlDataReader reader, stringcolumnName){//emaTable().ter = "ColumnName= '" + columnName + "'";//return(emaTable(). > 0);return emaTable().Select("ColumnName='" + columnName + "'").Length > 0;}public void Dispose(stringname){if(nsKey(name)){SqlCommand com=command[name];(name);e();}if ( <= 0)onnection();}public void Dispose(objecttran){List list =();h(o=>{if(command[o].Transaction!=null&&command[o].Transaction==(SqlTransaction)tran){e(o);}});}public object ToResult(IDbCode code, CommandType type =){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));object result =null;try{nnection();result=eScalar();}catch(Exception ex){DoException();throwex;}finally{e(name);onnection();}returnresult;}private voidDoException(){newDbException().Done();}public int ExcuteResult(IDbCode code, CommandType type =){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));int result = 0;try{nnection();if (tran != null)ction=(SqlTransaction)tran;result=eNonQuery();}catch(Exception ex){DoException();throwex;}finally{if (tran == null)Dispose(name);onnection();}returnresult;}public ble ToDataTable(IDbCode code, CommandType type =){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));DataTable dt= newDataTable();try{using(SqlDataAdapter adapter = newSqlDataAdapter(com)){(dt);}}catch(Exception ex){DoException();throwex;}finally{Dispose(name);}returndt;}public void setCommand(SqlCommand com,Listparas){h(o=>{(o);});}public t ToDataSet(IDbCode code, CommandType type =){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));DataSet dt= newDataSet();try{using (SqlDataAdapter adapter = newSqlDataAdapter(com)){(dt);}}catch(Exception ex){DoException();throwex;}finally{Dispose(name);}returndt;}public T ToModel(IDbCode code, CommandType type =)where T : class,new(){string name =ng();(name,newSqlCommand());SqlCommand com=command[name];tion=conn;dText=ng();dType=type;setCommand(com, (List));Type t= typeof(T);List p = null;if(nsKey()){p=pro[];}else{p=perties().ToList();(, p);}T model= newT();try{nnection();using(SqlDataReader reader =eReader()){if(()){h(o=>{if(ReaderExists(reader,)){ue(model, reader[],null);}});}}}catch(Exception ex){DoException();throwex;}finally{Dispose(name);onnection();}returnmodel;}public voidOpenConnection(){if ( !=)();}public voidCloseConnection(){().ForEach(o=>{if (ction != null)return;});if ( !=)();}public void BeginTransation(stringName){tran=ransaction(Name);}public voidCommit(){();Dispose(tran);tran= null;}public voidRollBack(){ck();Dispose(tran);tran= null;}}}具体类中,主要设计了最重要的执⾏⽅法外,还像刚开始所述,设置了List,就是⽤来存放command对象,在执⾏完成时候时候它会⾃⼰释放。跟这个类配合使⽤的是异常类:usingSystem;c;;;namespaceDal{public classDbException{public virtual voidDone(){}}}只有短短⼏句话,这就是⽤于使⽤者想发⽣异常想它⼲什么⽽设置的。其实封装到这⾥,整个框架的⽀持已经形成,但是⽤户不能直接操作底层,⽽且还需要怎么对数据库进⾏实例,所以还要对上进⾏封装,下⼀步,往上⾛,数据库实例部分。usingSystem;c;;;namespaceDal{public interfaceIDbInstance{//////数据库名称///stringName{get;}//////获取执⾏语句类///IDbExcute Excute{get;}//////获取连接字符串///stringConnectionString{get;}//////开启事务////// 事务名称///object getTransation(stringTranName);//////获取拼写字符串类///IDbCode Code{get;}}}实现它的具体类包含所有的底层的操作,其实就是可以说是⼀个数据库实例了,创建⼀个就相当于⼀个数据库。⾥⾯将上边封装的类都在这⾥使⽤。usingSystem;c;;;;e{public classSQLInstance :IDbInstance{privateSqlConnection conn;privateIDbExcute excute;Dictionary>pro;private stringname;private stringconnectionString;private SqlTransaction tran = null;publicSQLInstance(string Name,Dictionary> pro, stringConnectionString){ =Name;tionString =ConnectionString;conn= newSqlConnection(ConnectionString); =pro;excute= newSQLExcute(conn,pro);}public stringName{get{return ;}}publicIDbExcute Excute{get{return ;}}public stringConnectionString{get{return tionString;}}public object getTransation(stringTranName){return ransaction(TranName);}publicIDbCode Code{get{return newSQLCode(pro);}}}}接下来是控制连接的类:usingSystem;c;;;tion;namespaceDal{public classDbControl{//数据库服务private static Dictionary Server = new Dictionary();//存放缓存 private static Dictionary> pro = new Dictionary>();private staticDbControl control = newDbControl();public staticDbControl getInstance(){returncontrol;}privateDbControl(){}public IDbInstance createInstance(string Name,string ConnectionString,stringtype){string nspace = typeof(IDbInstance).Namespace;Type t= e(nspace + "." +type);object obj = Instance(t, new object[] { Name, pro,ConnectionString });IDbInstance instance= obj asIDbInstance;(Name, instance);returninstance;}public IDbInstance this[stringName]{get{if(nsKey(Name))returnServer[Name];elsereturn null;}}}}这⾥算是顶层的类,最主要就是存放数据库和缓存对象。也许会好奇如果存放数据库,还可以理解,但是放着模型对象的缓存,这是为什么?因为在字符连接,还有具体执⾏数据库语句时候都会使⽤到。⽽且,不仅这个数据库,别的数据库也会使⽤到,虽然在⼀个⼤项⽬可能⽤多个数据库,但是他们使⽤到项⽬⾥的模型是⼀致的吧,因此,将缓存设置在这⾥,最好不过。⽽且整个框架只有这⼀份,其他地⽅注⼊使⽤,就不会耗内存了。最后就是⽤户使⽤的部分,这部分已经屏蔽掉许多底层的部分,只留下通⽤⽅法。这些都已经封装好了,直接在这⾥调⽤就可以。usingSystem;c;;;;namespaceDal{public classDbHelper{privateIDbInstance instance;private stringName;privateDbControl control;privateIDbCode Code;publicDbHelper(){control=tance();}public DbHelper createConnection(string Name, string ConnectionString, stringtype){ =Name;instance=Instance(Name, ConnectionString, type);return this;}public DbHelper ExcuteString(FuncFun){Code= Fun();return this;}public DbHelper createTransation(stringName){ransation(Name);return this;}publicDbHelper Rollback(){ck();return this;}publicDbHelper Commit(){();return this;}public T ToModel(CommandType Type =)where T:class,new(){if ( == null)return null;return l(,Type);}List ToList(CommandType Type =)where T:class,new(){if ( == null)return null;return (, Type);}object ToResult(CommandType Type =){if ( == null)return null;return lt(, Type);}int ExcuteResult(CommandType Type =){if ( == null)return -1;return Result(, Type);}DataTable ToDataTable(CommandType Type=){if ( == null)return null;return Table(, Type);}DataSet ToDataSet(CommandType Type=){if ( == null)return null;return Set(, Type);}}}结束:快要熄灯了,没办法在写⽂章。如果⼤家对框架有什么不明⽩,可以在下⾯评论区问我。这就是更新之后的框架,我觉得还是蛮好⽤的,虽然还没经过严密的检测。有什么问题,⼤家也可以指导下,我也在学习中~