SqlHelper简单实现(通过Expression和反射)7.MySql数据处理类
MySql的数据处理类和Sql Server没有太大差别,从思路上来说没有区别,所以此处只是给出代码,不再多加解释了。
using System;
using System.Configuration;
using MySql.Data.MySqlClient;
using RA.DataAccess.Common; namespace RA.DataAccess.MySqlDbUtility
{
public partial class DbUtility : IDbUtility
{
private MySqlConnection conn;
private MySqlDataAdapter da;
private readonly string connectionString; private DbUtility()
{
connectionString = ConfigurationManager.AppSettings["MySql"];
}
private static DbUtility _dbUtility; public static DbUtility GetInstance()
{
return _dbUtility ?? (_dbUtility = new DbUtility());
} /// <summary>
/// 为通过反射生成的实例赋值
/// </summary>
/// <typeparam name="T">实例的类型</typeparam>
/// <param name="obj">实例</param>
/// <param name="value">值</param>
/// <param name="key">成员名称</param>
private void SetValue<T>(ref T obj, Object value, String key) where T : class
{
var property = obj.GetType().GetProperty(key);
var type = property.PropertyType.Name;
if (value is System.DBNull)
{
property.SetValue(obj, null, null);
return;
}
switch (type)
{
case "Int32":
property.SetValue(obj, int.Parse(value.ToString()), null);
break;
case "String":
property.SetValue(obj, value.ToString(), null);
break;
case "DateTime":
property.SetValue(obj, (DateTime)value, null);
break;
default:
property.SetValue(obj, value, null);
break;
}
}
/// <summary>
/// 获得SQLSession实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public SqlSession<T> GetSqlExpression<T>() where T : class
{
var temp = new SqlSession<T>();
conn = new MySqlConnection(connectionString);
return temp;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using MySql.Data.MySqlClient;
using RA.DataAccess.Common; namespace RA.DataAccess.MySqlDbUtility
{
public partial class DbUtility
{
/// <summary>
/// 获取列表,适用于单表查询
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="exp"></param>
/// <returns></returns>
public List<T> GetList<T>(SqlSession<T> exp) where T : class
{
var datatable = GetDataBySql<T>(exp.SqlExpression);
var result = new List<T>();
foreach (DataRow i in datatable.Rows)
{
T obj = Activator.CreateInstance<T>();
foreach (var k in exp.Fields)
{
SetValue(ref obj, i[k], k);
}
result.Add(obj);
}
return result;
} /// <summary>
/// 获取列表,适用于联表查询
/// </summary>
/// <typeparam name="Target">DTO类型</typeparam>
/// <typeparam name="T">exp代表的Entity类型</typeparam>
/// <param name="exp">SQLSession实例</param>
/// <returns>DTO列表</returns>
public List<Target> GetList<Target, T>(SqlSession<T> exp) where T : class where Target : class
{
var datatable = GetDataBySql<T>(exp.SqlExpression);
var result = new List<Target>(); foreach (DataRow i in datatable.Rows)
{
var obj = Activator.CreateInstance<Target>();
foreach (var k in EntityHelper.GetDTOFields<Target>())
{
SetValue(ref obj, i[k], k);
}
result.Add(obj);
}
return result;
} public List<T> Paged<T>(Expression<Func<T, object>> By, int pageIndex, int pageSize = ) where T : class
{
var result = new List<T>();
var sql = $@"SELECT * FROM {EntityHelper.GetTableName<T>()} ORDER BY {ExpressionHelper.GetSqlByExpression(By.Body)} LIMIT {pageIndex},{pageSize}";
conn = new MySqlConnection(connectionString);
conn.Open();
var datatable = GetDataBySql<T>(sql);
conn.Close();
foreach (DataRow i in datatable.Rows)
{
var obj = Activator.CreateInstance<T>();
foreach (var k in EntityHelper.GetFields<T>(false))
{
SetValue(ref obj, i[k], k);
}
result.Add(obj);
}
return result;
}
/// <summary>
/// 按照主键获取单条记录
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="func">筛选条件</param>
/// <returns>实体的实例</returns>
public T GetSingle<T>(Expression<Func<T, bool>> func) where T : class
{
var temptable = new DataTable();
var exp = ExpressionHelper.GetSqlByExpression(func.Body);
var fields = EntityHelper.GetFiledString<T>();
var tablename = EntityHelper.GetTableName<T>();
var sql = "SELECT " + fields + " FROM " + tablename + " WHERE " + exp;
conn = new MySqlConnection(connectionString);
da = new MySqlDataAdapter(sql, conn);
da.Fill(temptable);
if(temptable.Rows.Count == )
{
return null;
}
T obj = Activator.CreateInstance<T>();
foreach (var k in EntityHelper.GetFields<T>(false))
{
SetValue(ref obj, temptable.Rows[][k], k);
}
return obj;
} /// <summary>
/// 删除单个记录
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="func"></param>
public int Delete<T>(Expression<Func<T, bool>> func) where T : class
{
var tablename = EntityHelper.GetTableName<T>();
var exp = ExpressionHelper.GetSqlByExpression(func.Body);
var sql = "DELETE FROM " + tablename + " WHERE " + exp;
return RunSingleSql<T>(sql);
} /// <summary>
/// 添加单个记录
/// </summary>
/// <param name="obj"></param>
public int Add<T>(T obj) where T : class
{
var data = ObjectHelper.GetKeyValue(obj); var sql = "INSERT INTO {0}({1}) VALUES({2})";
var tablename = EntityHelper.GetTableName<T>();
var keys = string.Join(",", data.Keys.ToArray());
var values = string.Join(",", data.Values.Select(a => a == null ? "''" : "'" + a.ToString() + "'")); sql = string.Format(sql, tablename, keys, values); return RunSingleSql<T>(sql);
} /// <summary>
/// 执行除了Select以外的SQL,请不要在循环中使用这个方法,会有性能问题
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <returns></returns>
public int RunSingleSql<T>(string sql) where T : class
{
var conn = new MySqlConnection(connectionString);
var dc = new MySqlCommand(sql, conn); if (conn.State != ConnectionState.Open)
{
conn.Open();
}
try
{
return dc.ExecuteNonQuery();
}
finally
{
conn.Close();
}
} /// <summary>
/// 通过sql获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <returns></returns>
public DataTable GetDataBySql<T>(string sql) where T : class
{
var conn = new MySqlConnection(connectionString);
da = new MySqlDataAdapter(sql, conn);
var result = new DataTable();
da.Fill(result);
return result;
} /// <summary>
/// 更新一条记录
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">要修改的数据的Entity的实例</param>
/// <param name="func">要修改数据的条件</param>
/// <returns></returns>
public int Update<T>(T obj, Expression<Func<T, bool>> func) where T : class
{
if (func == null)
{
throw new ArgumentNullException("表达式不能为空!");
}
var tablename = EntityHelper.GetTableName<T>();
var data = ObjectHelper.GetKeyValue(obj);
var updatestr = data.Aggregate("", (current, i) => current + (i.Key + "='" + i.Value.ToString() + "',"));
updatestr = updatestr.Substring(, updatestr.Length - );
var where = ExpressionHelper.GetSqlByExpression(func.Body);
var sql = $"UPDATE {tablename} SET {updatestr} WHERE {@where}";
return RunSingleSql<T>(sql);
} /// <summary>
/// 批量添加记录
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
public int AddList<T>(List<T> objs) where T : class
{
if (!objs.Any())
{
throw new ArgumentNullException("列表为空!");
}
var tablename = EntityHelper.GetTableName(objs[].GetType());
var conn = new MySqlConnection(connectionString);
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
var transaction = conn.BeginTransaction();
var dc = conn.CreateCommand();
dc.Transaction = transaction;
var count = ;
try
{
foreach (var k in objs)
{
var data = new Dictionary<string, object>();
foreach (var i in k.GetType().GetProperties())
{
var value = k.GetType().GetProperty(i.Name).GetValue(k, null);
data.Add(i.Name, value);
}
var keys = string.Join(",", data.Keys.ToArray());
var values = string.Join(",", data.Values.Select(a => "'" + a.ToString() + "'"));
var sql = $"INSERT INTO {tablename}({keys}) VALUES({values})";
dc.CommandText = sql;
dc.ExecuteNonQuery();
count++;
}
transaction.Commit();
return count;
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
finally
{
conn.Close();
}
} /// <summary>
/// 获取总数
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="func">不传值的话,返回总数</param>
/// <returns></returns>
public int Count<T>(Expression<Func<T, bool>> func = null) where T : class
{
var tablename = EntityHelper.GetTableName<T>();
var sql = "";
if (func == null)
{
sql = $"SELECT COUNT(*) FROM {tablename}";
}
else
{
var where = ExpressionHelper.GetSqlByExpression(func.Body);
sql = $"SELECT COUNT(*) FROM {tablename} WHERE {@where}";
}
conn = new MySqlConnection(connectionString);
da = new MySqlDataAdapter(sql, conn);
var datatable = new DataTable();
da.Fill(datatable);
var result = (int)datatable.Rows[][];
return result;
} /// <summary>
/// 获取单个值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="Target"></typeparam>
/// <param name="field">字段名</param>
/// <param name="func">条件表达式</param>
/// <returns></returns>
public Target Scala<T,Target>(Expression<Func<T, Target>> field,Expression<Func<T,bool>> func)
{
var fieldname = ExpressionHelper.GetSqlByExpression(field.Body);
var exp = ExpressionHelper.GetSqlByExpression(func.Body);
var sql = $"SELECT {fieldname} FROM {EntityHelper.GetTableName<T>()} WHERE {exp}";
conn = new MySqlConnection(connectionString);
da = new MySqlDataAdapter(sql, conn);
var datatable = new DataTable();
da.Fill(datatable);
if(datatable.Rows.Count == )
{
return default(Target);
}
var result = (Target)datatable.Rows[][];
return result;
}
}
}
SqlHelper简单实现(通过Expression和反射)7.MySql数据处理类的更多相关文章
- SqlHelper简单实现(通过Expression和反射)1.引言
之前老大说要改变代码中充斥着各种Select的Sql语句字符串的情况,让我尝试着做一个简单的SqlHelper,要具有以下功能: 1.不要在业务代码中暴露DataTable或者DataSet类型: 2 ...
- 通过JAVA反射,调用未知类的类方法
下面是一个比较简单的通过JAVA的反射机制调用已知方法的例子 package com.togeek.mvntest; import java.lang.reflect.InvocationTarget ...
- Android利用反射机制为实体类属性赋值
在做android项目时,有时会遇到从网络上获取json类型数据,赋值给实体类,实体类属性少可以一个一个的赋值,如果实体类有很多属性,赋值可能就要耗很长的功夫了,幸好Java给我们提供了反射机制.下面 ...
- 透彻分析反射的基础_Class类
一.反射的基石--->Class类 1. Java类用于描述一类事物的特性,该类事物有什么属性,没有什么属性,值域这个属性的值是什么,则是由这个类的实例对象来确定的,不同的实例对象有不同的属性值 ...
- 反射 介绍System.Type类
本节先介绍system.Type类,通过这个类可以访问关于任何数据类型的信息. 1. system.Type类以前把Type看作一个类,但它实际上是一个抽象的基类.只要实例化了一个Type对象,实际上 ...
- C#用反射实现两个类的对象之间相同属性的值的复制
在进行实体转换操作的时候如果需要在对两个实体之间两个属性字段差不多相同的类要进行一个互相的转换,我们要把a对象的所有字段的值都复制给b对象,我们只能用b.属性=a.属性来写,如果属性字段太多的话,就要 ...
- Android面试基础(一)IOC(DI)框架(ViewUtils)讲解_反射和自定义注解类
1. Android中的IOC(DI)框架 1.1 ViewUtils简介(xUtils中的四大部分之一) IOC: Inverse of Controller 控制反转. DI: Dependenc ...
- 通过JDBC进行简单的增删改查(以MySQL为例) 目录
通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...
- Java通过JDBC进行简单的增删改查(以MySQL为例)
Java通过JDBC进行简单的增删改查(以MySQL为例) 目录: 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JD ...
随机推荐
- Oracle 常用性能监控SQL语句
1. --查看表锁 SELECT * FROM SYS.V_$SQLAREA WHERE DISK_READS > 100; 2. --监控事例的等待 SELECT EVEN ...
- asp.net网站防恶意刷新的Cookies与Session解决方法
本文实例讲述了asp.net网站防恶意刷新的Cookies与Session解决方法,是WEB程序设计中非常实用的技巧.分享给大家供大家参考.具体实现方法如下: Session版实现方法: public ...
- iOS从当前隐藏导航界面push到下一个显示导航界面出现闪一下的问题
本文转载至 http://blog.csdn.net/woaifen3344/article/details/41284319 navios 如果有朋友遇到从当前隐藏导航界面push到下一个显示导航界 ...
- iOS 程序切换后台
1. -(void)animationFinished:(NSString*)animationid finished:(NSNumber*)finished context:(void*)conte ...
- 爬虫入门【9】Python链接Excel操作详解-openpyxl库
Openpyx是一个用于读写Excel2010各种xlsx/xlsm/xltx/xltm文件的python库. 现在大多数用的都是office2010了,如果之前之前版本的可以使用xlrd读,xlwt ...
- salt常用命令、模块、执行
一.salt常用命令 salt 该命令执行salt的执行模块,通常在master端运行,也是我们最常用到的命令 salt [options] '<target>' <function ...
- 巨蟒python全栈开发-第16天 核能来袭-初识面向对象
一.今日内容总览(上帝视角,大象自己进冰箱,控制时机) #转换思想(从面向过程到面向对象) 1.初识面向对象 面向过程: 一切以事物的发展流程为中心. 面向对象: 一切以对象为中心,一切皆为对象,具体 ...
- 7.javascript如何调试代码
http://www.cnblogs.com/youring2/archive/2012/08/08/2624093.html
- 亚马逊 MWS 开发者指南 漏桶算法
流量控制与令牌桶算法|James Pan's Blog https://blog.jamespan.me/2015/10/19/traffic-shaping-with-token-bucket 服 ...
- MAC OSX--docker
http://www.cnblogs.com/yjmyzz/p/docker-install-tutorial.html http://www.cnblogs.com/yjmyzz/p/docker- ...