示例【1】

1、创建SQLHelper类

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Reflection; namespace Db
{
public class SQLHelper<T> where T : class, new()
{
/// <summary>
/// 链接数据库字符串
/// </summary>
public static string strConnectionString = ConfigurationManager.ConnectionStrings["DataConnectionString"].ToString();
/// <summary>
/// 数据库连接
/// </summary>
public SqlConnection Connection = null; public SQLHelper()
{
OpenConnect();
} /// <summary>
/// 打开数据库连接
/// </summary>
public void OpenConnect()
{
if (Connection == null || Connection.State != System.Data.ConnectionState.Open)
{
Connection = new SqlConnection(strConnectionString);
Connection.Open();
}
} /// <summary>
/// 关闭数据库连接
/// </summary>
public void CloseConnect()
{
if (Connection != null && Connection.State != System.Data.ConnectionState.Closed)
{
Connection.Close();
}
} #region 对数据库进行读写操作
/// <summary>
/// 执行查询语句
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="obQuery">SQL参数的值</param>
/// <returns></returns>
public SqlDataReader ExecReader(string strSQL, object obQuery)
{
SqlCommand command = new SqlCommand(strSQL, Connection);
if (obQuery != null)
{
PropertyInfo[] pis = obQuery.GetType().GetProperties();
foreach (var p in pis)
{
command.Parameters.Add(new SqlParameter(p.Name, p.GetValue(obQuery, null)));
}
}
SqlDataReader reader = command.ExecuteReader();
return reader;
} /// <summary>
/// 执行返回单值的查询语句
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="obQuery">SQL参数的值</param>
/// <returns></returns>
public object ExecSingleValue(string strSQL, object obQuery)
{
SqlCommand command = new SqlCommand(strSQL, Connection);
if (obQuery != null)
{
PropertyInfo[] pis = obQuery.GetType().GetProperties();
foreach (var p in pis)
{
command.Parameters.Add(new SqlParameter(p.Name, p.GetValue(obQuery, null)));
}
}
return command.ExecuteScalar();
} /// <summary>
/// 执行非查询语句
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="obQuery">SQL参数的值</param>
/// <returns></returns>
public int ExecNoQuery(string strSQL, object obQuery)
{
SqlCommand command = new SqlCommand(strSQL, Connection);
if (obQuery != null)
{
PropertyInfo[] pis = obQuery.GetType().GetProperties();
foreach (var p in pis)
{
command.Parameters.Add(new SqlParameter(p.Name, p.GetValue(obQuery, null)));
}
}
return command.ExecuteNonQuery();
}
#endregion #region 返回列表List<T>,利用"泛型+反射"
/// <summary>
/// 获取列表
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="obQuery">SQL参数的值</param>
/// <returns></returns>
public List<T> GetList(string strSQL, object obQuery)
{
//调用执行查询语句函数,返回SqlDataReader
SqlDataReader reader = ExecReader(strSQL, obQuery);
//定义返回的列表
List<T> list = new List<T>();
//定义T类型的实体
T model = new T();
//获取T类型实体的属性类型和值
PropertyInfo[] pis = model.GetType().GetProperties();
//获取数据库返回的列数
int intColCount = reader.FieldCount;
//遍历SqlDataReader
while (reader.Read())
{
//定义
int value_number = 0;
//重新实例化T
model = new T();
//从数据库拿出一条数据后,循环遍历T类型的属性类型和值
for (int i = 0; i < intColCount; i++)
{
//判断第一列是否为row_number,此为分页使用
if (reader.GetName(i) == "row_number") value_number++;
//设置T对应属性的值
pis[i].SetValue(model, reader.GetValue(value_number), null);
value_number++;
}
//将T添加到列表中
list.Add(model);
}
return list;
}
#endregion /// <summary>
/// 获取分页
/// </summary>
/// <param name="strTotalSQL">总共个数的SQL</param>
/// <param name="obTotalQuery">总共个数的SQL参数的值</param>
/// <param name="strSQL">分页的SQL</param>
/// <param name="obQuery">分页SQL参数的值</param>
/// <param name="intPageIndex">分页编号</param>
/// <param name="intPageSize">分页大小</param>
/// <returns>返回PagesList<T></returns>
public PagedList<T> GetPageList(string strTotalSQL, object obTotalQuery, string strSQL, object obQuery, int intPageIndex, int intPageSize)
{
//定义分页对象的编号和大小
PagedList<T> pageList = new PagedList<T>(intPageIndex, intPageSize);
//执行获取单个值的函数,设置分页对象的总元素
pageList.intTotalCount = (int)ExecSingleValue(strTotalSQL, obTotalQuery);
//设置分页对象的分页数
if (pageList.intTotalCount % intPageSize == 0) pageList.intPages = pageList.intTotalCount / intPageSize;
else pageList.intPages = pageList.intTotalCount / intPageSize + 1;
//定义列表,调用获取列表的函数获取此分页的元素
List<T> list = GetList(strSQL, obQuery);
//将列表元素添加到分页对象当中
pageList.AddRange(list);
//设置分页对象是否有上一页和下一页
pageList.HasNextPage = pageList.intPageIndex < pageList.intPages ? true : false;
pageList.HasPrPage = pageList.intPageIndex > 1 ? true : false;
return pageList;
} /// <summary>
/// 获取单个实体
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="obQuery">SQL参数的值</param>
/// <returns></returns>
public T GetTM(string strSQL, object obQuery)
{
//调用执行查询语句,返回SqlDataReader
SqlDataReader reader = ExecReader(strSQL, obQuery);
//新建一个T类型
T model = new T();
//获取T类型的属性类型和值
PropertyInfo[] pis = model.GetType().GetProperties();
//获取数据库返回数据的列数
int intColCount = reader.FieldCount;
//读取数据,填充T
if (reader.Read())
{
int value_number = 0;
for (int i = 0; i < intColCount; i++)
{
pis[i].SetValue(model, reader.GetValue(value_number), null);
value_number++;
}
}
return model;
}
} /// <summary>
/// 分页实体类
/// </summary>
/// <typeparam name="T"></typeparam>
public class PagedList<T> : List<T>
{
/// <summary>
/// 分页编号
/// </summary>
public int intPageIndex { get; set; }
/// <summary>
/// 分页大小
/// </summary>
public int intPageSize { get; set; }
/// <summary>
/// 分页数
/// </summary>
public int intPages { get; set; }
/// <summary>
/// 总元素的个数
/// </summary>
public int intTotalCount { get; set; }
/// <summary>
/// 此分页元素的个数
/// </summary>
public int intCount { get; set; }
/// <summary>
/// 是否有下一页
/// </summary>
public bool HasNextPage { get; set; }
/// <summary>
/// 是否有上一页
/// </summary>
public bool HasPrPage { get; set; }
public PagedList(int intPageIndex, int intPageSize)
{
this.intPageIndex = intPageIndex;
this.intPageSize = intPageSize;
}
}
}

2、调用方法

// 调用方法:ResumeTM 为数据库表的实体类
public List<ResumeTM> GetResumeByJobInfoId(int intJobInfoId)
{
SQLHelper<ResumeTM> helper = new SQLHelper<ResumeTM>();
string strSQL = @"select * from Resume where FirstJobId=@JobInfoId or SecondJobId=@JobInfoId order by CreateTime desc";
object obQuery = new { JobInfoId = intJobInfoId };
List<ResumeTM> list = helper.GetList(strSQL, obQuery);
helper.CloseConnect();
return list;
} public ResumeTM GetResumeById(int intId)
{
SQLHelper<ResumeTM> helper = new SQLHelper<ResumeTM>();
string strSQL = @"select * from Resume where Id=@Id";
object obQuery = new { Id = intId };
ResumeTM tm = helper.GetTM(strSQL, obQuery);
helper.CloseConnect();
return tm;
} public PagedList<ResumeTM> GetResume(int intPageIndex, int intPaegSize)
{
SQLHelper<ResumeTM> helper = new SQLHelper<ResumeTM>();
string strTotalCount = @"select count(*) from Resume";
string strSQL = @"select * from
(select row_number() over(order by CreateTime desc) as row_number,* from Resume) as t0
where t0.row_number between @intPageSize*(@intPageIndex-1)+1 and @ingPageSize*@intPageIndex";
object obQuery = new { intPageSize = intPaegSize, intPageIndex = intPageIndex };
PagedList<ResumeTM> list = helper.GetPageList(strTotalCount, null, strSQL, obQuery, intPageIndex, intPaegSize);
helper.CloseConnect();
return list;
} public void Delete(int intId)
{
SQLHelper<ResumeTM> helper = new SQLHelper<ResumeTM>();
string strSQL = @"delete from Resume where Id=@Id";
object obQuery = new { Id = intId };
helper.ExecNoQuery(strSQL, obQuery);
helper.CloseConnect();
}

示例【2】

1、定义实体类

public class BaseModel
{
public int Id { set; get; }
} public class Company : BaseModel
{
public string Name { get; set; }
public System.DateTime CreateTime { get; set; }
public int CreatorId { get; set; }
public int? LastModifierId { get; set; }
public DateTime? LastModifyTime { get; set; }
} public class User : BaseModel
{
public string Name { get; set; }
public string Account { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public int? CompanyId { get; set; }
public string CompanyName { get; set; }
public int State { get; set; }
public int UserType { get; set; }
public DateTime? LastLoginTime { get; set; }
public DateTime CreateTime { get; set; }
public int CreatorId { get; set; }
public int? LastModifierId { get; set; }
}

2、编写通用接口

public interface IBaseDAL
{
T FindT<T>(int id) where T : BaseModel;
List<T> FindAll<T>() where T : BaseModel;
bool Add<T>(T t) where T : BaseModel;
bool Update<T>(T t) where T : BaseModel;
bool Delete<T>(T t) where T : BaseModel;
}

3、使用"泛型+反射"实现接口

public class BaseDAL : IBaseDAL
{
public T FindT<T>(int id) where T : BaseModel
{
Type type = typeof(T);
string sql = $"SELECT {string.Join(",", type.GetProperties().Select(p => $"[{p.Name}]"))} FROM [{type.Name}] WHERE ID={id}";
using (SqlConnection conn = new SqlConnection(ConnectionStringCustomers))
{
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
var reader = command.ExecuteReader();
if (reader.Read())
{
return this.Trans<T>(type, reader);
}
else
{
return null;
}
}
} private T Trans<T>(Type type, SqlDataReader reader)
{
object oObject = Activator.CreateInstance(type);
foreach (var prop in type.GetProperties())
{
prop.SetValue(oObject, reader[prop.Name] is DBNull ? null : reader[prop.Name]);
}
} public List<T> FindAll<T>() where T : BaseModel
{
Type type = typeof(T);
string sql = $"SELECT {string.Join(",", type.GetProperties().Select(p => $"[{p.Name}]"))} FROM [{type.Name}]";
using (SqlConnection conn = new SqlConnection(ConnectionStringCustomers))
{
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
var reader = command.ExecuteReader();
List<T> tList = new List<T>();
while (reader.Read())
{
tList.Add(this.Trans<T>(type, reader));
}
return tList;
}
}
public bool Add<T>(T t) where T : BaseModel
{
//id是自增的 所以不能新增
Type type = t.GetType();
string columnString = string.Join(",", type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)
.Select(p => $"[{p.Name}]"));
string valueColumn = string.Join(",", type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)
.Select(p => $"@{p.Name}"));
var parameterList = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)
.Select(p => new SqlParameter($"@{p.Name}", p.GetValue(t) ?? DBNull.Value));//注意可空类型 string sql = $"Insert [{type.Name}] ({columnString}) values({valueColumn})";
using (SqlConnection conn = new SqlConnection(ConnectionStringCustomers))
{
SqlCommand command = new SqlCommand(sql, conn);
command.Parameters.AddRange(parameterList.ToArray());
conn.Open();
return command.ExecuteNonQuery() == 1;
//新增后把id拿出来? 可以的,在sql后面增加个 Select @@Identity; ExecuteScalar
}
}
}

C# 泛型SQLHelper<T>类的更多相关文章

  1. DataReader,DataTable利用泛型填充实体类

    using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary ...

  2. 微软版的SqlHelper.cs类

    一,微软SQLHelper.cs类 中文版: using System; using System.Data; using System.Xml; using System.Data.SqlClien ...

  3. 微软SQLHelper.cs类 中文版

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Co ...

  4. 微软SQLHelper.cs类

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

  5. SQLHelper帮助类_下(支持多数据库的封装)

    在上篇关于SQLHelper类中,主要针对SQLServer数据库进行的.在使用别的数据库,就要修改部分代码!所以今天就写一个支持多数据库的封装!主要用到枚举,读取config文件!接口的简单用法.获 ...

  6. C#工具:反射帮助类 泛型反射帮助类

    反射帮助类 using System; using System.Reflection; using System.Data; using System.Drawing; using System.R ...

  7. JAVA基础--JAVA 集合框架(泛型、file类)16

    一.集合总结 集合:Collection体系.Map体系. Collection体系:单列集合的共性操作规则. List:列表,可以重复,有下标,拥有特有的迭代器ListIterator. Array ...

  8. 处女篇:自用C#后端SqlHelper.cs类

    自用SqlHelper.cs类,此类来自软谋教育徐老师课程SqlHelper.cs! using System; using System.Collections; using System.Coll ...

  9. JAVA基础--JAVA 集合框架(泛型、file类)

    一.集合总结 集合:Collection体系.Map体系. Collection体系:单列集合的共性操作规则. List:列表,可以重复,有下标,拥有特有的迭代器ListIterator. Array ...

  10. C#版SQLHelper.cs类

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

随机推荐

  1. Django——前后端分离出现同源策略的解决方式

    浏览器控制台报错:"Access-Control-Allow-Origin" 解决方式:在Django服务端解决 1.安装django-cors-headers(可能需要先更新pi ...

  2. Vue——Ajax请求的基本使用

    1.get方法发送Ajax请求 // 直接在 URL 上添加参数 ID=12345 axios.get('/user?ID=12345') .then(function (response) { co ...

  3. 莫烦tensorflow学习记录 (2)激励函数Activation Function

    https://mofanpy.com/tutorials/machine-learning/tensorflow/intro-activation-function/ 这里的 AF 就是指的激励函数 ...

  4. 对于 EI K 逆序对排列计数的另一种自然求和方法的理解

    有一个简单的 \(O(n^3)\) DP,考虑 \(f_{x + 1, k} = \sum_{j = 0}^{x} f_{x, k - j}\),利用前缀和优化即可. 考虑这实际上是 \(f_{x + ...

  5. docker日常使用操作场景

    日常使用场景 场景1:将自己的镜像从hub中拉取,并压缩成tar.gz文件 # 首先拉取镜像 docker pull docker.images.hub/{namespace}/{servicenam ...

  6. go 1.6 废弃 io/ioutil 包后的替换函数

    go 1.6 废弃 io/ioutil  包后的替换函数 io/ioutil 替代 ioutil.ReadAll -> io.ReadAll ioutil.ReadFile -> os.R ...

  7. idea编译报错 静态Map初始化报错java.lang.ExceptionInInitializerError

    idea编译报错 静态Map初始化报错java.lang.ExceptionInInitializerError package cc.mrbird.utils; import java.util.H ...

  8. 幻想领域图床系统V1.2正式版发布

    Tips:当你看到这个提示的时候,说明当前的文章是由原emlog博客系统搬迁至此的,文章发布时间已过于久远,编排和内容不一定完整,还请谅解` 幻想领域图床系统V1.2正式版发布 日期:2018-4-1 ...

  9. fastadmin的导出到excel功能

    正常的excel导出没什么问题,最近一直头疼的是怎么导出数据中包含图片,并且图片还是数组?????by user 悦悦 https://www.cnblogs.com/nuanai 1.导出的exce ...

  10. HDU1010第一道DFS

    DFS就是深度搜索算法....感觉就像破案一样.... #include<iostream> #include<cstdio> #include<cstring> ...