SQLSERVER单表CRUD通用方法

时间:2022-09-16 23:55:10

一、适用场景

  ①当你书写简单的增删改查心累了

  ②当你的项目不考虑并发、高性能

  ③当你追求更快速的开发效率

  ④当你的业务只涉及单表

二、代码展示

  ①单表Insert

  
 public bool Insert<T>(T t)
{
var o = t.GetType();
var sBulider = new StringBuilder("insert into ");
sBulider.Append("[" + o.Name + "]");
sBulider.Append("(");
var properties = o.GetProperties();
foreach (var p in properties)
{
sBulider.Append(p.Name);
sBulider.Append(",");
}
sBulider.Length--;
sBulider.Append(") values(");
foreach (var p in properties)
{
sBulider.AppendFormat("'{0}'", p.GetValue(t, null));
sBulider.Append(",");
}
sBulider.Length--;
sBulider.Append(")");
return SqlDBHelper.ExecuteSql(sBulider.ToString()) > ;
}

  ②单表Delete

  
  public bool Delete<T>(string idList) where T : new()
{
var tableName = new T().GetType().Name;
var ids = new StringBuilder();
foreach (var id in idList.Split(','))
{
ids.Append("'");
ids.Append(id);
ids.Append("',");
}
ids.Length--;
var sql = string.Format("delete from [{0}] where Id in ({1})", tableName, ids.ToString());
return SqlDBHelper.ExecuteSql(sql) > ;
}

  ③单表Update

  
 public bool Update<T>(T t)
{
var o = t.GetType();
var sBulider = new StringBuilder("update ");
sBulider.Append("[" + o.Name + "]");
sBulider.Append(" set ");
var id = "";
var properties = o.GetProperties();
foreach (var p in properties)
{
var columnName = p.Name;
var columnValue = p.GetValue(t, null);
if (columnName == "Id")
id = columnValue.ToString();
sBulider.Append(columnName);
sBulider.AppendFormat("='{0}'", columnValue);
sBulider.Append(",");
}
sBulider.Length--;
sBulider.AppendFormat("where Id='{0}'", id);
return SqlDBHelper.ExecuteSql(sBulider.ToString()) > ;
}

  ④单表Select

  
 public List<T> SerarchList<T>(string where = "") where T : new()
{
var tableName = new T().GetType().Name;
var sqlString = new StringBuilder();
sqlString.AppendFormat("select * from [{0}]", tableName);
if (!string.IsNullOrEmpty(where))
{
sqlString.AppendFormat(" where '{0}'", where);
}
var list = new List<T>();
using (var dataReader = SqlDBHelper.ExecuteReader(sqlString.ToString()))
{
while (dataReader.Read())
{
var t = new T();
var properties = t.GetType().GetProperties();
foreach (var p in properties)
{
p.SetValue(t, dataReader[p.Name], null);
}
list.Add(t);
}
}
return list;
}

三、局限性

  ①实体类名字必须和表名一致

  ②主键名必须为Id

  ③不适合自增型主键

  ④出现问题难以调试(可以添加日志跟踪)

  ⑤安全性低(暴漏字段名)

  ⑥实现分页太暴力

  ⑦灵活性低(通用和灵活永远的矛盾体)

  ⑧Update操作时会全表更新

  ⑨Select操作会全字段查询

四、源码下载

  sourcecode