public class OrmHelper
{
private string constr = "server=.;uid=sa;pwd=1234;database=mySchool00100";
private string GetInsert<T>(T t)
{
Type t1 = t.GetType();// 获取对应的type
var ps = t1.GetProperties();// 获取所有属性
var fields = string.Join(",", ps.Where(p => p.Name.ToLower() != "id").Select(p => p.Name));
var values = string.Join(",", ps.Where(p => p.Name.ToLower() != "id").Select(p => "'" + p.GetValue(t) + "'"));
return string.Format("insert into {0} ({1}) values ({2})", t1.Name, fields, values);
}
private string GetSelect<T>()
{
Type t1 = typeof(T);// 获取对应的type
var ps = t1.GetProperties();// 获取所有属性
var fields = string.Join(",", ps.Select(p => p.Name));
return string.Format("select {0} from {1}", fields, t1.Name);
}
private string GetDelete<T>(T t)
{
Type t1 = t.GetType();// 获取对应的type
return string.Format("delete from {0} where Id={1}", t1.Name, t1.GetProperty("Id").GetValue(t));
}
private string GetUpdate<T>(T t)
{
Type t1 = t.GetType();// 获取对应的type
var ps = t1.GetProperties();// 获取所有属性
var fields = string.Join(",", ps.Where(p => p.Name.ToLower() != "id").Select(p => p.Name + "='" + p.GetValue(t) + "'"));
return string.Format("update {0} set {1} where Id={2} ", t1.Name, fields, t1.GetProperty("Id").GetValue(t));
}
private int ExecuteNonQuery(string sql)
{
using (SqlConnection scon = new SqlConnection(constr))
{
scon.Open();
SqlCommand scom = new SqlCommand(sql, scon);
int result = scom.ExecuteNonQuery();
scon.Close();
return result;
}
}
public int Add<T> (T t) where T : new()
{
string sql = GetInsert(t);
return ExecuteNonQuery(sql);
}
public int Update<T>(T t) where T : new()
{
string sql = GetUpdate(t);
return ExecuteNonQuery(sql);
}
public int Delete<T>(T t) where T : new()
{
string sql = GetDelete(t);
return ExecuteNonQuery(sql);
}
public List<T> Select<T>() where T : new()
{
List<T> list = new List<T>();
var Ps = typeof(T).GetProperties();
string sql = GetSelect<T>();
using (SqlConnection scon = new SqlConnection(constr))
{
scon.Open();
SqlCommand scom = new SqlCommand(sql, scon);
SqlDataReader reader = scom.ExecuteReader();
while (reader.Read())
{
T t1 = new T();
foreach (var p in Ps)
{
p.SetValue(t1, reader[p.Name]);
}
list.Add(t1);
}
reader.Close();
scon.Close();
return list;
}
}
}
用反射来实现增删改查语句
最新推荐文章于 2022-06-12 12:44:56 发布