ADO.Net数据库帮助类
public interface IDBHelper
{
/// <summary>
/// 执行sql语句
/// </summary>
/// <param name="sql"></param>
void ExecuteNonQuery(string sql, SqlParameter[] sqlParams = null);
/// <summary>
/// 执行sql返回单一结果
/// </summary>
/// <param name="sql"></param>
/// <param name="sqlParams"></param>
object ExecuteScalar(string sql, SqlParameter[] sqlParams = null);
/// <summary>
/// 事务执行sql
/// </summary>
/// <param name="sql"></param>
void ExecuteTrans(string sql, SqlParameter[] sqlParams = null);
/// <summary>
/// 获取单个实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"></param>
/// <returns></returns>
T QuerySingle<T>(T model,string tableName = null) where T : class, new(); /// <summary>
/// 查询数据表的全部数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
IEnumerable<T> QueryAll<T>(string tableName = null) where T : class, new(); /// <summary>
/// 插入实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
void Insert<T>(T model, string tableName = null) where T : class, new(); /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
void InsertList<T>(IEnumerable<T> list, string tableName = null) where T : class, new();
/// <summary>
/// 更新实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
void Update<T>(T model, string tableName = null) where T : class, new(); /// <summary>
/// 根据Id删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"></param>
/// <returns></returns>
void Delete<T>(T model, string tableName = null) where T : class, new();
}
public class SQLHelper : IDBHelper
{
private string connString; public SQLHelper(string connString = null)
{
if(!string.IsNullOrEmpty(connString))
{
this.connString = connString;
}
else
{
this.connString = ConfigurationManager.ConnectionStrings["connString"].ToString();
}
} #region 执行sql语句
/// <summary>
/// 执行sql语句
/// </summary>
/// <param name="sql"></param>
public void ExecuteNonQuery(string sql, SqlParameter[] sqlParams = null)
{
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
if (sqlParams != null)
cmd.Parameters.AddRange(sqlParams);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// 执行sql语句,返回单一结果
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public object ExecuteScalar(string sql, SqlParameter[] sqlParams = null)
{
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
if (sqlParams != null)
cmd.Parameters.AddRange(sqlParams);
return cmd.ExecuteScalar();
}
}
/// <summary>
/// 事务执行sql
/// </summary>
/// <param name="sql"></param>
public void ExecuteTrans(string sql, SqlParameter[] sqlParams = null)
{
SqlTransaction trans = null;
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
trans = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand(sql, conn);
if (sqlParams != null)
cmd.Parameters.AddRange(sqlParams);
cmd.ExecuteNonQuery();
trans.Commit();
}
}
catch (Exception ex)
{
if (trans != null && trans.Connection != null)
trans.Rollback();
throw ex;
}
}
#endregion #region 根据实体增删改查
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="tableName"></param>
/// <returns></returns>
public void Delete<T>(T model, string tableName = null) where T : class, new()
{
Type type = typeof(T);
if (type.GetProperty("Id") == null)
{
throw new ArgumentNullException(string.Format("实体{0}必须包含主键Id字段", type.Name));
}
string _tableName = GetTableName<T>(tableName);
var Id = type.GetProperty("Id").GetValue(model);
string txtSql = string.Format("Delete from [{0}] Where Id=@id", _tableName);
ExecuteNonQuery(txtSql, new[] { new SqlParameter("@id", Id) });
}
/// <summary>
/// 插入
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="tableName"></param>
/// <returns></returns>
public void Insert<T>(T model, string tableName = null) where T : class, new()
{
Type type = typeof(T);
SqlParameter[] sqlParams = type.GetProperties().Where(p => p.Name != "Id").Select(s => new SqlParameter(string.Format("@{0}", s.Name), s.GetValue(model) ?? DBNull.Value)).ToArray();
string txtSql = GetInsertSql(model, tableName);
var result = ExecuteScalar(txtSql, sqlParams);
var idProperty = type.GetProperty("Id");
idProperty.SetValue(model,Convert.ChangeType(result, idProperty.PropertyType));//将插入生成的Id赋值给model }
/// <summary>
/// 插入多个实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="tableName"></param>
public void InsertList<T>(IEnumerable<T> list, string tableName = null) where T : class, new()
{
Type type = typeof(T);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
foreach (var item in list)
{
SqlParameter[] sqlParams = type.GetProperties().Where(p => p.Name != "Id").Select(s => new SqlParameter(string.Format("@{0}", s.Name), s.GetValue(item) ?? DBNull.Value)).ToArray();
string txtSql = GetInsertSql<T>(item, tableName);
SqlCommand cmd = new SqlCommand(txtSql, conn);
if (sqlParams != null)
cmd.Parameters.AddRange(sqlParams);
var result = cmd.ExecuteScalar();
var idProperty = type.GetProperty("Id");
idProperty.SetValue(item, Convert.ChangeType(result, idProperty.PropertyType));//将插入生成的Id赋值给model
}
}
}
/// <summary>
/// 查询单个实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="tableName"></param>
/// <returns></returns>
public T QuerySingle<T>(T model, string tableName = null) where T : class, new()
{
Type type = typeof(T);
if (type.GetProperty("Id") == null)
{
throw new ArgumentNullException(string.Format("实体{0}必须包含主键Id字段", type.Name));
}
string _tableName = GetTableName<T>(tableName);
var Id = type.GetProperty("Id").GetValue(model);
string selectField = string.Join(",", type.GetProperties().Select(s => string.Format("[{0}]", s.Name)));
string txtSql = string.Format("select {0} from [{1}] where Id =@id", selectField, _tableName);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(txtSql, conn);
cmd.Parameters.Add(new SqlParameter("@id",Id));
SqlDataReader reader = cmd.ExecuteReader();
return ReaderToEntity<T>(reader);
}
}
/// <summary>
/// 查询所有
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public IEnumerable<T> QueryAll<T>(string tableName = null) where T : class, new()
{
Type type = typeof(T);
string selectField = string.Join(",", type.GetProperties().Select(p => string.Format("[{0}]", p.Name)));
string txtSql = string.Format("select {0} from [{1}]", selectField, type.Name);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(txtSql, conn);
SqlDataReader reader = cmd.ExecuteReader();
return ReaderToList<T>(reader);
}
}
/// <summary>
/// 更新
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="tableName"></param>
public void Update<T>(T model, string tableName = null) where T : class, new()
{
Type type = typeof(T);
if (type.GetProperty("Id") == null)
{
throw new ArgumentNullException(string.Format("实体{0}必须包含主键Id字段", type.Name));
}
string _tableName = GetTableName<T>(tableName);
string setCloums = string.Join(",", type.GetProperties().Where(p => p.Name != "Id").Select(s => string.Format("[{0}]=@{0}", s.Name)));
string txtSql = string.Format("update [{0}] set {1} where Id =@id",_tableName,setCloums);
SqlParameter[] sqlParams = type.GetProperties().Select(s => new SqlParameter(string.Format("@{0}", s.Name), s.GetValue(model) ?? DBNull.Value)).ToArray();
ExecuteNonQuery(txtSql, sqlParams);
}
#endregion #region private
private string GetTableName<T>(string tableName)
{
string result = tableName;
if (string.IsNullOrEmpty(result))//如果参数tableName为空
{
//1.检查[tableName]属性
Type type = typeof(T);
var tableNameAttribute = (TableNameAttribute)type.GetCustomAttributes(typeof(TableNameAttribute), false).FirstOrDefault();
if (tableNameAttribute != null)
{
result = tableNameAttribute.TableName;
}
if (string.IsNullOrEmpty(result))
{
//2.[tableName]属性为空 用实体名称
result = type.Name;
}
} return result;
} private string GetInsertSql<T>(T model,string tableName)
{
Type type = typeof(T);
if (type.GetProperty("Id") == null)
{
throw new ArgumentNullException(string.Format("实体{0}必须包含主键Id字段", type.Name));
}
string _tableName = GetTableName<T>(tableName);
string txtColums = string.Join(",", type.GetProperties().Where(p => p.Name != "Id").Select(s => string.Format("[{0}]", s.Name)));
string txtValues = string.Join(",", type.GetProperties().Where(p => p.Name != "Id").Select(s => string.Format("@{0}", s.Name)));
string txtSql = string.Format("insert into [{0}] ({1}) values({2});select @@identity;", _tableName, txtColums, txtValues);
return txtSql;
} private T ReaderToEntity<T>(SqlDataReader reader) where T : class, new()
{
T entity = new T();
if (reader.Read())
{
Type type = typeof(T);
foreach (var item in type.GetProperties())
{
object oValue = reader[item.Name];
if (oValue is DBNull)
{
item.SetValue(entity, null);
}
else
{
item.SetValue(entity, oValue);
}
}
}
return entity;
} private IEnumerable<T> ReaderToList<T>(SqlDataReader reader) where T : class, new()
{
List<T> list = new List<T>();
if (reader.Read())
{
Type type = typeof(T);
do
{
T entity = new T();
foreach (var item in type.GetProperties())
{
object oValue = reader[item.Name];
if (oValue is DBNull)
{
item.SetValue(entity, null);
}
else
{
item.SetValue(entity, oValue);
}
}
list.Add(entity);
}
while (reader.Read());
}
return list;
}
#endregion
}
ADO.Net数据库帮助类的更多相关文章
- ADO.NET 数据库操作类
操作数据类 避免代码重用.造对象太多.不能分工开发 利用面向对象的方法,把数据访问的方式优化一下,利用封装类 一般封装成三个类: 1.数据连接类 提供数据连接对象 需要引用命名空间: using ...
- ADO.NET数据库操作助手类
SQL语句操作增删查改助手类 using System; using System.Collections.Generic; using System.Configuration; using Sys ...
- 我也来写:数据库访问类DBHelper
一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以 ...
- 我也来写:数据库访问类DBHelper(转)
一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以 ...
- 一个通用数据库访问类(C#,SqlClient)
本文转自:http://www.7139.com/jsxy/cxsj/c/200607/114291.html使用ADO.NET时,每次数据库操作都要设置connection属性.建立connecti ...
- ADO.Net 数据库查询
数据库中的表: VS查询代码: using System; using System.Collections.Generic; using System.Linq; using System.Text ...
- VC++下使用ADO操作数据库
VC++下使用ADO操作数据库主要要用到 _ConnectionPtr,_CommandPtr,_RecordsetPtr三个ADO对象指针,我查找了相关资料,发现网上源码很多,但是都相对凌乱,于是自 ...
- ADO.NET数据库编程
ADO.NET数据库编程 1.ADO.NET的相关概念. Microsoft的新一代技术,是ADO组件的后继者. 主要目的是在.NET Framework平台存取数据. 提供一致的对象模型,可以存取和 ...
- 学习实践:使用模式,原则实现一个C++数据库访问类
一.概述 在我参与的多个项目中,大家使用libMySQL操作MySQL数据库,而且是源码即复用,在多个项目中有多套相同或相似的源码,这样的复用方式给开发带来了不变,而且libMySQL的使用比较麻烦, ...
随机推荐
- [SCOI2016]美味(可持久化线段树)
可持久化trie树?好像和可持久化权值线段树差不多.. 如果这题没有那个\(x[i]\)这题就是一个裸的可持久化trie树. 仔细想想,多了这个\(x[i]\)之后有什么影响? 就是我们查询区间的时候 ...
- jquery 取页面中ifram中得节点
<iframe src="html/bai.jsp" frameBorder=0 id=middle name=middle scrolling="yes" ...
- mac同时享受教育优惠和免手续费分期
神奇地址:工商银行 http://store.apple.com/cn_icbc_edu招商银行 http://store.apple.com/cn_cmb_edu农业银行 http://sto ...
- Git学习总结(7)——Git GUI学习教程
前言 之前一直想一篇这样的东西,因为最初接触时,我也认真看了廖雪峰的教程,但是似乎我觉得讲得有点多,而且还是会给我带来很多多余且重复的操作负担,所以我希望能压缩一下它在我工作中的成本,但是搜索了一下并 ...
- Mysql 日期型,索引查询的问题
问题: 表中,有一个日期字段WorkDate(Date YYYY-MM-DD格式),现在我把它建成了索引,在检索条件时,WorkDate='YYYY-MM-DD' 时,用EXPLAIN分析,能看到使用 ...
- httpd: Could not reliably determine the server's fully qualified domain name
[root@luozhonghua sbin]# service httpd start Starting httpd: httpd: apr_sockaddr_info_get() failed f ...
- hdu2236
链接:点击打开链接 题意:在一个n*n的矩阵中,找n个数使得这n个数都在不同的行和列里而且要求这n个数中的最大值和最小值的差值最小 代码: #include <iostream> #inc ...
- 拥抱PBO(基于项目的组织)聚焦核心价值创造
近年来.PBO(Project-Based Organizations)作为一种新兴的整合各类专业智力资源和专业知识的组织结构,受到越来越多的关注,第五版PMBOK出现的新词汇.三种组织(职能型.矩阵 ...
- mysql---左连接、右连接、内连接之间的差别与联系
现有两张表 第一张表为男生表,记录了男生的姓名和配偶的编号 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbXlfbWFv/font/5a6L5L2T/fo ...
- Windows 绝赞应用(该网站收集了日常好用的工具和软件)
在我们的电脑使用过程中,或多或少的被流氓软件恶心过.流氓软件之所以这么流氓全是靠他那恐怖的用户数量,基本上形成垄断后,各种流氓行为就一点点体现出来了. 我们也可以选择不用,但对流氓软件来说多你一个不多 ...