反射ORM 三层,for sql server/mysql

sql server and oracle 不同之处只在于:

1·参数@和:

2·自增和序列

RPROM.cs //(写错愕,应该是RPORM)

RPROM.Insert(p1); //需求:DBS中插入一条数据

约定:

类名要和表名一样

字段名和数据库列名一样

主键的名字必须是Id,必须自动递增,int类型

class RupengROM

{

/// 插入对象

internal static void Insert(Object obj)

{

//获得类名

Type type = obj.GetType();

string className = type.Name;

//获得除id的所有列名

PropertyInfo[] properties = type.GetProperties();

string[] propertyNames = new string[properties.Length - 1]; //存除id的属性名(列名)

string[] propertyAtNames = new string[properties.Length - 1]; //存除id的属性+@名

//获得除id的所有参数

MySqlParameter[] mysqlParameters = new MySqlParameter[properties.Length - 1]; //存除id的参数名

int i = 0;

foreach(PropertyInfo property in properties)

{

if(property.Name!="Id")

{

propertyNames[i] = property.Name;

propertyAtNames[i] = "@" + property.Name;

MySqlParameter mysqlParam = new MySqlParameter();

mysqlParam.ParameterName = "@" + property.Name;

mysqlParam.Value = property.GetValue(obj); //获得指定对象的属性值

mysqlParameters[i] = mysqlParam;

i++;

}

}

string propertyNamesStr = string.Join(",", propertyNames);

string propertyAtNamesStr = string.Join(",", propertyAtNames);

//拼接sql语句

//insert into T_Person(Name,Age) values(@Name,@Age)

StringBuilder sb = new StringBuilder();

sb.Append("insert into T_").Append(className).Append("(").Append(propertyNamesStr).Append(") values(").Append(propertyAtNamesStr).Append(")");

int im = MySqlHelper.ExecuteNonQuery(sb.ToString(), mysqlParameters);

string msg = im > 0 ? "插入成功" : "插入失败";

Console.WriteLine(msg);

}

/// 根据id查询对象

internal static Object SelectById(Type type,int id)

{

string className = type.Name;

//拼接sql语句

//select * from T_Person where Id=@Id

StringBuilder sb = new StringBuilder();

sb.Append("select * from T_").Append(className).Append(" where );

DataTable dt = MySqlHelper.ExecuteQuery(sb.ToString(), new MySqlParameter() { ParameterName = "@Id", Value = id });

if(dt.Rows.Count<=0)

{

return null;

}

else if(dt.Rows.Count>1)

{

throw new Exception("数据库发生异常,存在;

Console.WriteLine(msg);

}

}