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数据库帮助类的更多相关文章

  1. ADO.NET 数据库操作类

    操作数据类 避免代码重用.造对象太多.不能分工开发 利用面向对象的方法,把数据访问的方式优化一下,利用封装类   一般封装成三个类: 1.数据连接类 提供数据连接对象 需要引用命名空间: using ...

  2. ADO.NET数据库操作助手类

    SQL语句操作增删查改助手类 using System; using System.Collections.Generic; using System.Configuration; using Sys ...

  3. 我也来写:数据库访问类DBHelper

    一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以 ...

  4. 我也来写:数据库访问类DBHelper(转)

    一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以 ...

  5. 一个通用数据库访问类(C#,SqlClient)

    本文转自:http://www.7139.com/jsxy/cxsj/c/200607/114291.html使用ADO.NET时,每次数据库操作都要设置connection属性.建立connecti ...

  6. ADO.Net 数据库查询

    数据库中的表: VS查询代码: using System; using System.Collections.Generic; using System.Linq; using System.Text ...

  7. VC++下使用ADO操作数据库

    VC++下使用ADO操作数据库主要要用到 _ConnectionPtr,_CommandPtr,_RecordsetPtr三个ADO对象指针,我查找了相关资料,发现网上源码很多,但是都相对凌乱,于是自 ...

  8. ADO.NET数据库编程

    ADO.NET数据库编程 1.ADO.NET的相关概念. Microsoft的新一代技术,是ADO组件的后继者. 主要目的是在.NET Framework平台存取数据. 提供一致的对象模型,可以存取和 ...

  9. 学习实践:使用模式,原则实现一个C++数据库访问类

    一.概述 在我参与的多个项目中,大家使用libMySQL操作MySQL数据库,而且是源码即复用,在多个项目中有多套相同或相似的源码,这样的复用方式给开发带来了不变,而且libMySQL的使用比较麻烦, ...

随机推荐

  1. jQuery第三课 点击按钮 弹出层div效果

    jQuery 事件方法 事件方法会触发匹配元素的事件,或将函数绑定到所有匹配元素的某个事件. 触发实例: $("button#demo").click() 上面的例子将触发 id= ...

  2. 紫书 习题 8-25 UVa 11175 (结论证明)(配图)

    看了这篇博客https://blog.csdn.net/u013520118/article/details/48032599 但是这篇里面没有写结论的证明, 我来证明一下. 首先结论是对于E图而言, ...

  3. macOS seria 10.12升级到macOS Mojave的报错:xcrun: error: invalid active developer path, missing xcrun

    今天升级mac系统到macOS mojave后,在终端操作gitlab时遇到一行莫名其妙的错误: xcrun: error: invalid active developer path (/Libra ...

  4. Windows和Linux的编译理解

    Windows一般编译出来的x86的软件,就是只能在x86的系统上才能运行,同理,在x64系统上也是一样的道理. Linux利用gcc编译器编译,可以在Linux上面运行,但是想要在嵌入式系统上运行的 ...

  5. 洛谷—— P2904 [USACO08MAR]跨河River Crossing

    https://www.luogu.org/problem/show?pid=2904 题目描述 Farmer John is herding his N cows (1 <= N <= ...

  6. DBCA创建数据库ORA-01034 ORACLE not available

    SYMPTOMS 在利用dbca创建数据库时,当设置完毕全部參数.開始装时 跑到2% 就报错 ORA-01034 ORACLE not available, 例如以下图 watermark/2/tex ...

  7. 【HDU 5145】 NPY and girls(组合+莫队)

    pid=5145">[HDU 5145] NPY and girls(组合+莫队) NPY and girls Time Limit: 8000/4000 MS (Java/Other ...

  8. 解决The hierarchy of the type is inconsistent错误

    可能的原因:自己的类继承于某个类,这个类或者这个类继承的类或者再往上继承的某个类所在的jar包没有被引入. 比如:使用Spring的AOP时,假设须要继承MethodBeforeAdvice和Afte ...

  9. wsimport 使用方法具体解释

    wsimport 使用方法 本文主要介绍wsimport的简单使用方法.帮助大家在webserviceclient开发过程中生成接口代码: 打开java JDK文件夹我们会看到wsimport工具,这 ...

  10. JavaWeb利用cookie记住账号

    JavaWeb利用cookie记住账号. 首先,来看看界面什么样子. 记住账号最普遍的做法,就是在点击登录时,将账号保存到cookie中. 材料准备 <script src="${ct ...