分享
 
 
 

ORM小练习代码

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: |||超大  

DOG类

namespaceRupengORM

{publicclassDog

{publicDog()

{

}///<summary>///显示提供无参构造函数///</summary>///<param name="aa"></param>publicDog(intaa)

{

}publicintId {get;set; }publicstringName {get;set; }publicintWeight {set;get; }

}

}

Sqlhelper:

usingSystem.Collections.Generic;usingSystem.Configuration;usingSystem.Data;usingMySQL.Data.MySqlClient;namespaceRupengORM

{publicclassDbSqlhelper

{PRivatestaticreadonlystringSqlconnstr = ConfigurationManager.ConnectionStrings["mysqlconn"].ConnectionString;publicstaticMySqlConnection CreateConnection()

{

MySqlConnection conn=newMySqlConnection(Sqlconnstr);

conn.Open();returnconn;

}publicstaticintExecuteNonQuery(MySqlConnection conn,stringsql,paramsMySqlParameter[] parameters)

{using(MySqlCommand cmd=conn.CreateCommand())

{

cmd.CommandText=sql;

cmd.Parameters.AddRange(parameters);returncmd.ExecuteNonQuery();

}

}publicstaticintExecuteNonQuery(stringsql,paramsMySqlParameter [] parameters)

{using(MySqlConnection conn =CreateConnection())

{returnExecuteNonQuery(conn, sql, parameters);

}

}publicstaticobjectExecuteScalar(MySqlConnection conn,stringsql, Dictionary<string,object>dictionary)

{using(MySqlCommand cmd=conn.CreateCommand())

{

cmd.CommandText=sql;foreach(varkvpindictionary)

{

IDbDataParameter parameter=cmd.CreateParameter();

parameter.ParameterName=kvp.Key;

parameter.Value=kvp.Value;

cmd.Parameters.Add(parameter);

}returncmd.ExecuteScalar();

}

}publicstaticobjectExecuteScalar(stringsql, Dictionary<string,object>dictionary)

{using(MySqlConnection conn=CreateConnection())

{returnExecuteScalar(conn, sql, dictionary);

}

}publicstaticDataTable ExecuteQuery(MySqlConnection conn,stringsql, Dictionary<string,object>dictionary)

{

DataTable dataTable=newDataTable();using(MySqlCommand cmd=conn.CreateCommand())

{

cmd.CommandText=sql;foreach(varkvpindictionary)

{

IDbDataParameter parameter=cmd.CreateParameter();

parameter.ParameterName=kvp.Key;

parameter.Value=kvp.Value;

cmd.Parameters.Add(parameter);using(IDataReader reader=cmd.ExecuteReader())

{

dataTable.Load(reader);

}

}

}returndataTable;

}publicstaticDataTable ExecuteQuery(stringsql, Dictionary<string,object>dictionary)

{using(MySqlConnection conn=CreateConnection())

{returnExecuteQuery(conn, sql, dictionary);

}

}

}

}

RProm 实现过程:

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingMySql.Data.MySqlClient;namespaceRupengORM

{internalclassRPorm

{//约定:1、类名要和表名一样//2、字段名和数据库列名一样//3、主键的名字必须叫Id,必须是自动递增,int类型//////////publicstaticvoidInsert(objectobj)

{//获得obj对象的类名vartype = obj.GetType();//typeof(Person)varclassName = type.Name;//类名:Person//propertyInfos获得类里面所有的属性varpropertyInfos =type.GetProperties();varpropNames =newstring[propertyInfos.Length -1];//排除掉IdvarparamNames =newstring[propertyInfos.Length -1];varsqlParameters =newMySqlParameter[propertyInfos.Length -1];//Dictionary<string, object> dic = new Dictionary<string, object>();varcount =0;foreach(varpropInfoinpropertyInfos)

{varpropName =propInfo.Name;if(propName !="Id")//排除Id{//遍历赋值,包含ID不进入赋值propNames[count] =propName;

paramNames[count]="@"+propName;varmySqlParameter =newMySqlParameter();

mySqlParameter.ParameterName="@"+propName;

mySqlParameter.Value= propInfo.GetValue(obj);//去obj对象属性的值sqlParameters[count] =mySqlParameter;

count++;

}

}//拼接生成insert语句varsbSql =newStringBuilder();

sbSql.Append("insert into")

.Append(className)

.Append("(")

.Append(string.Join(",", propNames))

.Append(")");

sbSql.Append("values (").Append(string.Join(",", paramNames)).Append(")");

DbSqlhelper.ExecuteNonQuery(sbSql.ToString(), sqlParameters);//params可变长度参数本质上就是一个数组}publicstaticobjectSelectById(Type type,intid)

{//将表名获取到varclassname =type.Name;varsql ="select * from"+ classname +"where id=@id";vardictionary =newDictionary<string,object>();

dictionary["@id"] =id;vardataTable =DbSqlhelper.ExecuteQuery(sql, dictionary);if(dataTable.Rows.Count <=0)

{returnnull;

}if(dataTable.Rows.Count >1)

{thrownewException("查到多条ID="+ id +"的数据");

}varrow = dataTable.Rows[0];//创建type类的一个对象varobj =Activator.CreateInstance(type);//给obj对象的每一个属性(包括Id)赋值,得到id name weightforeach(varpropInfointype.GetProperties())

{varpropName = propInfo.Name;//属性名就是别名varvalue = row[propName];//获取数据库中列的值propInfo.SetValue(obj, value);//给obj对象的propinfo属性赋值为value}returnobj;

}publicstaticT SelectById<T>(intid)whereT :new()//泛型约束,约束T必须有一个无参的构造函数{vartype =typeof(T);//typeof(Person)varclassname =type.Name;varsql ="select * from"+ classname +"where id=@id";vardictionary =newDictionary<string,object>();

dictionary["@id"] =id;vardataTable =DbSqlhelper.ExecuteQuery(sql, dictionary);if(dataTable.Rows.Count <=0)

{returndefault(T);//default(T)运算符用来获得类型的默认值//default(int)→0 default(bool)→false default(Person)→null}if(dataTable.Rows.Count >1)

{thrownewException("查到多条ID="+ id +"的数据");

}varrow = dataTable.Rows[0];//创建type类的一个对象//var obj = Activator.CreateInstance(type);varobj =newT();//泛型约束//给obj对象的每一个属性(包括Id)赋值 返回当前 Type 的所有公共属性。foreach(varpropInfointype.GetProperties())

{varpropName = propInfo.Name;//属性名就是别名varvalue = row[propName];//获取数据库中列的值propInfo.SetValue(obj, value);//给obj对象的propinfo属性赋值为value}returnobj;

}publicstaticboolDeleteById(Type type,intid)

{varclassname =type.Name;varsql ="delete from"+ classname +"where id=@id";vari = DbSqlhelper.ExecuteNonQuery(sql,newMySqlParameter {ParameterName ="@id", Value =id});//delete from dog where name='孔老二4'returni >0;

}publicstaticboolUpdateById(objectobj)

{vartype =obj.GetType();varclassname = type.Name;//获得表名varpropertyInfos = type.GetProperties();//获得表名中的功能属性varpropNames =newstring[propertyInfos.Length];//获取该属性的长度varparamNames =newstring[propertyInfos.Length];varsqlParameters =newMySqlParameter[propertyInfos.Length];varcount =0;foreach(varpropInfoinpropertyInfos)

{varpropName =propInfo.Name;varmySqlParameter =newMySqlParameter();

mySqlParameter.ParameterName="@"+propName;

mySqlParameter.Value= propInfo.GetValue(obj);//去obj对象属性的值sqlParameters[count] =mySqlParameter;if(propName !="Id")//排除Id{//遍历赋值,包含ID不进入赋值propNames[count] = propName;//nameparamNames[count]= propName +"=@"+ propName;//@name}

count++;

}varoop =string.Join(",", paramNames).Substring(4);//sqlParameters;varsb =newStringBuilder();

sb.Append("update").Append(classname).Append("set").Append(oop).Append("where id=@id");varsqltxt =sb.ToString();vari =DbSqlhelper.ExecuteNonQuery(sqltxt, sqlParameters);//生成update语句//update dog set name=@name weight=@weight where id=@id//怎么知道那一列被修改了呢//把所有列都更新一下。反正不变的还是不变returni >0;

}

}

}

主程序:

usingSystem;namespaceRupengORM

{internalclassProgram

{privatestaticvoidMain(string[] args)

{//ORM:EF(entity framework,Dapper,Nhibernate)//Person p1=new Person();//p1.Name = "rupeng";//p1.Age = 7;//RPorm.Insert(p1);for(vari =0; i <10; i++)

{vard1 =newDog();

d1.Name="孔老二"+i;

d1.Weight=30;

RPorm.Insert(d1);

}//Person p1 = (Person)RPorm.SelectById(typeof(Person),1);//Console.WriteLine(p1.Name+"的年龄是"+p1.Age);//Dog p2 = (Dog)RPorm.SelectById(typeof(Dog), 1);//if (p2 == null)//{//Console.WriteLine("没找到狗");//}//else//{//Console.WriteLine(p2.Name);//}//Dog dog = RPorm.SelectById<Dog>(1);//Console.WriteLine(dog.Name);//Type type = new Type typeof(Dog);//bool aa= RPorm.DeleteById(typeof(Dog),2);//Console.WriteLine(aa);vardog =newDog();

dog.Weight++;

dog.Name="孔老二";

dog.Id=9;varupdate =RPorm.UpdateById(dog);

Console.WriteLine(update);

Console.ReadKey();

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有