using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;
using System.IO;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
namespace DAL
{
public class DBhelp
{
public string Add<T>(T list) {
//获取任意类中的类型
var t1 = typeof(T);
//获取类型中的属性
PropertyInfo[] prp = t1.GetProperties();
//拼接添加的sql
string str="insert into "+t1.Name+" values(";
//声明变量
int i = 0;
//循环遍历属性
foreach (PropertyInfo item in prp)
{
i++;
//判断主键的值是否为空
if (item.GetCustomAttribute(typeof(KeyAttribute),true)==null)
{
//当i的大小等于数组的长度是在SQL的结尾加上)否则拼接字段
if (i== prp.Length)
{
str+= "'"+item.GetValue(list) + "')";
}
else
{
str +="'" +item.GetValue(list) + "',";
}
}
}
//返回SQL
return str;
}
//删除
public string Del<T>(T model, int id)
{
var t1 = typeof(T);
PropertyInfo[] prp = t1.GetProperties();
string str = "";
foreach (var item in prp)
{
str+=("delete from " + t1.Name + " where " + item.Name + "=")+id;
break;
}
return str;
}
public string Look<T>(T stu)
{
var type = typeof(T);
//新建StringBuilder
string str = "select * from " + type.Name;
//接收查询到的数据表
return str;
}
public string Edit<T>(T model, int id)
{
//获取当前实体
var tt = typeof(T);
//获取属性
PropertyInfo[] propertyInfos = tt.GetProperties();
//新建动态字符串
string str = "";
str += "update " + tt.Name + " set ";
int i = 0;
//循环元素
foreach (var item in propertyInfos)
{
i++;//截止当前已经走过的元素数
if (item.GetCustomAttribute(typeof(KeyAttribute), true) == null)
{
//如果是最后一个元素
if (i == propertyInfos.Length)
{
str += item.Name + "='" + item.GetValue(model) + "'";
}
else
{
str += item.Name + "='" + item.GetValue(model) + "'";
}
}
}
//循环输出
foreach (var item in propertyInfos)
{
str += "where " + item.Name + "=" + id;
break;
}
return str;
}
}
}