MySqlHelper、CacheHelper
MySqlHelper代码:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Configuration;
- using System.Data;
- using MySql.Data.MySqlClient;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Web;
- using System.Xml.Linq;
- using System.Data.Objects.DataClasses;
- using Models;
- using System.Text.RegularExpressions;
- namespace DBHelper
- {
- /// <summary>
- /// MySql操作类
- /// 2015年6月20日
- /// 写程序之前,首先引用MySql.Data.MySqlClient
- /// </summary>
- public class MySqlHelper
- {
- #region 静态变量
- /// <summary>
- /// 数据库连接字符串
- /// </summary>
- private static string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
- #endregion
- #region MySqlConnection 获取数据库连接
- /// <summary>
- /// 获取数据库连接
- /// </summary>
- private static MySqlConnection GetConn()
- {
- MySqlConnection connection = null;
- string key = "Simpo2016_MySqlConnection";
- if (HttpContext.Current.Items[key] == null)
- {
- connection = new MySqlConnection(connectionString);
- connection.Open();
- HttpContext.Current.Items[key] = connection;
- }
- else
- {
- connection = (MySqlConnection)HttpContext.Current.Items[key];
- }
- return connection;
- }
- #endregion
- #region MySqlTransaction 获取事务对象
- /// <summary>
- /// 获取事务对象
- /// </summary>
- private static MySqlTransaction GetTran()
- {
- MySqlTransaction tran = null;
- string key = "Simpo2016_MySqlTransaction";
- if (HttpContext.Current.Items[key] == null)
- {
- tran = GetConn().BeginTransaction();
- HttpContext.Current.Items[key] = tran;
- }
- else
- {
- tran = (MySqlTransaction)HttpContext.Current.Items[key];
- }
- return tran;
- }
- #endregion
- #region 开起事务标志
- /// <summary>
- /// 事务标志
- /// </summary>
- private static string tranFlagKey = "Simpo2016_MySqlTransaction_Flag";
- /// <summary>
- /// 添加事务标志
- /// </summary>
- public static void AddTranFlag()
- {
- HttpContext.Current.Items[tranFlagKey] = true;
- }
- /// <summary>
- /// 移除事务标志
- /// </summary>
- public static void RemoveTranFlag()
- {
- HttpContext.Current.Items[tranFlagKey] = false;
- }
- /// <summary>
- /// 事务标志
- /// </summary>
- public static bool TranFlag
- {
- get
- {
- bool tranFlag = false;
- if (HttpContext.Current.Items[tranFlagKey] != null)
- {
- tranFlag = (bool)HttpContext.Current.Items[tranFlagKey];
- }
- return tranFlag;
- }
- }
- #endregion
- #region 用于查询的数据库连接
- /// <summary>
- /// 用于查询的数据库连接
- /// </summary>
- private MySqlConnection m_Conn;
- #endregion
- #region 构造函数
- public MySqlHelper()
- {
- m_Conn = new MySqlConnection(connectionString);
- }
- #endregion
- #region 基础方法
- #region 执行简单SQL语句
- #region Exists
- public bool Exists(string sqlString)
- {
- using (MySqlCommand cmd = new MySqlCommand(sqlString, m_Conn))
- {
- try
- {
- m_Conn.Open();
- object obj = cmd.ExecuteScalar();
- if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- cmd.Dispose();
- m_Conn.Close();
- }
- }
- }
- #endregion
- #region 执行SQL语句,返回影响的记录数
- /// <summary>
- /// 执行SQL语句,返回影响的记录数
- /// </summary>
- /// <param name="sqlString">SQL语句</param>
- /// <returns>影响的记录数</returns>
- public int ExecuteSql(string sqlString)
- {
- MySqlConnection connection = GetConn();
- using (MySqlCommand cmd = new MySqlCommand(sqlString, connection))
- {
- try
- {
- if (connection.State != ConnectionState.Open) connection.Open();
- if (TranFlag) cmd.Transaction = GetTran();
- int rows = cmd.ExecuteNonQuery();
- return rows;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- finally
- {
- cmd.Dispose();
- if (!TranFlag) connection.Close();
- }
- }
- }
- #endregion
- #region 执行一条计算查询结果语句,返回查询结果
- /// <summary>
- /// 执行一条计算查询结果语句,返回查询结果(object)
- /// </summary>
- /// <param name="sqlString">计算查询结果语句</param>
- /// <returns>查询结果(object)</returns>
- public object GetSingle(string sqlString)
- {
- using (MySqlCommand cmd = new MySqlCommand(sqlString, m_Conn))
- {
- try
- {
- m_Conn.Open();
- object obj = cmd.ExecuteScalar();
- if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
- {
- return null;
- }
- else
- {
- return obj;
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- cmd.Dispose();
- m_Conn.Close();
- }
- }
- }
- #endregion
- #region 执行查询语句,返回SQLiteDataReader
- /// <summary>
- /// 执行查询语句,返回SQLiteDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
- /// </summary>
- /// <param name="sqlString">查询语句</param>
- /// <returns>SQLiteDataReader</returns>
- public MySqlDataReader ExecuteReader(string sqlString)
- {
- MySqlConnection connection = new MySqlConnection(connectionString);
- MySqlCommand cmd = new MySqlCommand(sqlString, connection);
- try
- {
- connection.Open();
- MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
- return myReader;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- #endregion
- #region 执行查询语句,返回DataSet
- /// <summary>
- /// 执行查询语句,返回DataSet
- /// </summary>
- /// <param name="sqlString">查询语句</param>
- /// <returns>DataSet</returns>
- public DataSet Query(string sqlString)
- {
- using (MySqlConnection connection = new MySqlConnection(connectionString))
- {
- DataSet ds = new DataSet();
- try
- {
- connection.Open();
- MySqlDataAdapter command = new MySqlDataAdapter(sqlString, connection);
- command.Fill(ds, "ds");
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- connection.Close();
- }
- return ds;
- }
- }
- #endregion
- #endregion
- #region 执行带参数的SQL语句
- #region 执行SQL语句,返回影响的记录数
- /// <summary>
- /// 执行SQL语句,返回影响的记录数
- /// </summary>
- /// <param name="SQLString">SQL语句</param>
- /// <returns>影响的记录数</returns>
- public int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
- {
- MySqlConnection connection = GetConn();
- using (MySqlCommand cmd = new MySqlCommand())
- {
- try
- {
- PrepareCommand(cmd, connection, null, SQLString, cmdParms);
- if (TranFlag) cmd.Transaction = GetTran();
- int rows = cmd.ExecuteNonQuery();
- cmd.Parameters.Clear();
- return rows;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- cmd.Dispose();
- if (!TranFlag) connection.Close();
- }
- }
- }
- #endregion
- #region 执行查询语句,返回SQLiteDataReader
- /// <summary>
- /// 执行查询语句,返回SQLiteDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
- /// </summary>
- /// <param name="strSQL">查询语句</param>
- /// <returns>SQLiteDataReader</returns>
- public MySqlDataReader ExecuteReader(string sqlString, params MySqlParameter[] cmdParms)
- {
- MySqlCommand cmd = new MySqlCommand();
- try
- {
- PrepareCommand(cmd, m_Conn, null, sqlString, cmdParms);
- MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
- cmd.Parameters.Clear();
- return myReader;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- #endregion
- #region 执行查询语句,返回DataSet
- /// <summary>
- /// 执行查询语句,返回DataSet
- /// </summary>
- /// <param name="sqlString">查询语句</param>
- /// <returns>DataSet</returns>
- public DataSet Query(string sqlString, params MySqlParameter[] cmdParms)
- {
- MySqlCommand cmd = new MySqlCommand();
- PrepareCommand(cmd, m_Conn, null, sqlString, cmdParms);
- using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
- {
- DataSet ds = new DataSet();
- try
- {
- da.Fill(ds, "ds");
- cmd.Parameters.Clear();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- cmd.Dispose();
- m_Conn.Close();
- }
- return ds;
- }
- }
- #endregion
- #region PrepareCommand
- private void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
- {
- if (conn.State != ConnectionState.Open) conn.Open();
- cmd.Connection = conn;
- cmd.CommandText = cmdText;
- if (trans != null) cmd.Transaction = trans;
- cmd.CommandType = CommandType.Text;
- if (cmdParms != null)
- {
- foreach (MySqlParameter parm in cmdParms)
- {
- cmd.Parameters.Add(parm);
- }
- }
- }
- #endregion
- #endregion
- #endregion
- #region 增删改查
- #region 获取最大编号
- /// <summary>
- /// 获取最大编号
- /// </summary>
- /// <typeparam name="T">实体Model</typeparam>
- /// <param name="key">主键</param>
- public int GetMaxID<T>(string key)
- {
- Type type = typeof(T);
- string sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
- using (MySqlCommand cmd = new MySqlCommand(sql, m_Conn))
- {
- try
- {
- m_Conn.Open();
- object obj = cmd.ExecuteScalar();
- if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
- {
- return ;
- }
- else
- {
- return int.Parse(obj.ToString()) + ;
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- cmd.Dispose();
- m_Conn.Close();
- }
- }
- }
- #endregion
- #region 添加
- /// <summary>
- /// 添加
- /// </summary>
- public void Insert(object obj)
- {
- StringBuilder strSql = new StringBuilder();
- Type type = obj.GetType();
- CacheHelper.Remove(type);//删除缓存
- strSql.Append(string.Format("insert into {0}(", type.Name));
- PropertyInfo[] propertyInfoList = GetEntityProperties(type);
- List<string> propertyNameList = new List<string>();
- foreach (PropertyInfo propertyInfo in propertyInfoList)
- {
- propertyNameList.Add(propertyInfo.Name);
- }
- strSql.Append(string.Format("{0})", string.Join(",", propertyNameList.ToArray())));
- strSql.Append(string.Format(" values ({0})", string.Join(",", propertyNameList.ConvertAll<string>(a => "@" + a).ToArray())));
- MySqlParameter[] parameters = new MySqlParameter[propertyInfoList.Length];
- for (int i = ; i < propertyInfoList.Length; i++)
- {
- PropertyInfo propertyInfo = propertyInfoList[i];
- object val = propertyInfo.GetValue(obj, null);
- MySqlParameter param = new MySqlParameter("@" + propertyInfo.Name, val == null ? DBNull.Value : val);
- parameters[i] = param;
- }
- ExecuteSql(strSql.ToString(), parameters);
- }
- #endregion
- #region 修改
- /// <summary>
- /// 修改
- /// </summary>
- public void Update(object obj)
- {
- object oldObj = Find(obj, false);
- if (oldObj == null) throw new Exception("无法获取到旧数据");
- StringBuilder strSql = new StringBuilder();
- Type type = obj.GetType();
- CacheHelper.Remove(type);//删除缓存
- strSql.Append(string.Format("update {0} ", type.Name));
- PropertyInfo[] propertyInfoList = GetEntityProperties(type);
- List<string> propertyNameList = new List<string>();
- int savedCount = ;
- foreach (PropertyInfo propertyInfo in propertyInfoList)
- {
- object oldVal = propertyInfo.GetValue(oldObj, null);
- object val = propertyInfo.GetValue(obj, null);
- if (!object.Equals(oldVal, val))
- {
- propertyNameList.Add(propertyInfo.Name);
- savedCount++;
- }
- }
- strSql.Append(string.Format(" set "));
- MySqlParameter[] parameters = new MySqlParameter[savedCount];
- StringBuilder sbPros = new StringBuilder();
- int k = ;
- for (int i = ; i < propertyInfoList.Length; i++)
- {
- PropertyInfo propertyInfo = propertyInfoList[i];
- object oldVal = propertyInfo.GetValue(oldObj, null);
- object val = propertyInfo.GetValue(obj, null);
- if (!object.Equals(oldVal, val))
- {
- sbPros.Append(string.Format(" {0}=@{0},", propertyInfo.Name));
- MySqlParameter param = new MySqlParameter("@" + propertyInfo.Name, val == null ? DBNull.Value : val);
- parameters[k++] = param;
- }
- }
- if (sbPros.Length > )
- {
- strSql.Append(sbPros.ToString(, sbPros.Length - ));
- }
- strSql.Append(string.Format(" where {0}='{1}'", GetIdName(obj.GetType()), GetIdVal(obj).ToString()));
- if (savedCount > )
- {
- ExecuteSql(strSql.ToString(), parameters);
- }
- }
- #endregion
- #region 删除
- /// <summary>
- /// 根据Id删除
- /// </summary>
- public void Delete<T>(int id)
- {
- Type type = typeof(T);
- CacheHelper.Remove(type);//删除缓存
- StringBuilder sbSql = new StringBuilder();
- sbSql.Append(string.Format("delete from {0} where {2}='{1}'", type.Name, id, GetIdName(type)));
- ExecuteSql(sbSql.ToString());
- }
- /// <summary>
- /// 根据Id集合删除
- /// </summary>
- public void BatchDelete<T>(string ids)
- {
- if (string.IsNullOrWhiteSpace(ids)) return;
- Type type = typeof(T);
- CacheHelper.Remove(type);//删除缓存
- StringBuilder sbSql = new StringBuilder();
- sbSql.Append(string.Format("delete from {0} where {2} in ({1})", type.Name, ids, GetIdName(type)));
- ExecuteSql(sbSql.ToString());
- }
- /// <summary>
- /// 根据条件删除
- /// </summary>
- public void Delete<T>(string conditions)
- {
- if (string.IsNullOrWhiteSpace(conditions)) return;
- Type type = typeof(T);
- CacheHelper.Remove(type);//删除缓存
- StringBuilder sbSql = new StringBuilder();
- sbSql.Append(string.Format("delete from {0} where {1}", type.Name, conditions));
- ExecuteSql(sbSql.ToString());
- }
- #endregion
- #region 获取实体
- #region 根据实体获取实体
- /// <summary>
- /// 根据实体获取实体
- /// </summary>
- private object Find(object obj, bool readCache = true)
- {
- Type type = obj.GetType();
- object result = Activator.CreateInstance(type);
- bool hasValue = false;
- IDataReader rd = null;
- string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, GetIdVal(obj), GetIdName(obj.GetType()));
- //获取缓存
- if (readCache && CacheHelper.Exists(type, sql))
- {
- return CacheHelper.Get(type, sql);
- }
- try
- {
- rd = ExecuteReader(sql);
- PropertyInfo[] propertyInfoList = GetEntityProperties(type);
- int fcnt = rd.FieldCount;
- List<string> fileds = new List<string>();
- for (int i = ; i < fcnt; i++)
- {
- fileds.Add(rd.GetName(i).ToUpper());
- }
- while (rd.Read())
- {
- hasValue = true;
- IDataRecord record = rd;
- foreach (PropertyInfo pro in propertyInfoList)
- {
- if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
- {
- continue;
- }
- pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (rd != null && !rd.IsClosed)
- {
- rd.Close();
- rd.Dispose();
- }
- }
- if (hasValue)
- {
- CacheHelper.Add(type, sql, result);//添加缓存
- return result;
- }
- else
- {
- return null;
- }
- }
- #endregion
- #region 根据Id获取实体
- /// <summary>
- /// 根据Id获取实体
- /// </summary>
- private object FindById(Type type, int id)
- {
- object result = Activator.CreateInstance(type);
- IDataReader rd = null;
- bool hasValue = false;
- string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));
- //获取缓存
- if (CacheHelper.Exists(type, sql))
- {
- return CacheHelper.Get(type, sql);
- }
- try
- {
- rd = ExecuteReader(sql);
- PropertyInfo[] propertyInfoList = GetEntityProperties(type);
- int fcnt = rd.FieldCount;
- List<string> fileds = new List<string>();
- for (int i = ; i < fcnt; i++)
- {
- fileds.Add(rd.GetName(i).ToUpper());
- }
- while (rd.Read())
- {
- hasValue = true;
- IDataRecord record = rd;
- foreach (PropertyInfo pro in propertyInfoList)
- {
- if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
- {
- continue;
- }
- pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (rd != null && !rd.IsClosed)
- {
- rd.Close();
- rd.Dispose();
- }
- }
- if (hasValue)
- {
- CacheHelper.Add(type, sql, result);//添加缓存
- return result;
- }
- else
- {
- return null;
- }
- }
- #endregion
- #region 根据Id获取实体
- /// <summary>
- /// 根据Id获取实体
- /// </summary>
- public T FindById<T>(string id) where T : new()
- {
- Type type = typeof(T);
- T result = (T)Activator.CreateInstance(type);
- IDataReader rd = null;
- bool hasValue = false;
- string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));
- //获取缓存
- if (CacheHelper.Exists(type, sql))
- {
- return (T)CacheHelper.Get(type, sql);
- }
- try
- {
- rd = ExecuteReader(sql);
- PropertyInfo[] propertyInfoList = GetEntityProperties(type);
- int fcnt = rd.FieldCount;
- List<string> fileds = new List<string>();
- for (int i = ; i < fcnt; i++)
- {
- fileds.Add(rd.GetName(i).ToUpper());
- }
- while (rd.Read())
- {
- hasValue = true;
- IDataRecord record = rd;
- foreach (PropertyInfo pro in propertyInfoList)
- {
- if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
- {
- continue;
- }
- pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (rd != null && !rd.IsClosed)
- {
- rd.Close();
- rd.Dispose();
- }
- }
- if (hasValue)
- {
- CacheHelper.Add(type, sql, result);//添加缓存
- return result;
- }
- else
- {
- return default(T);
- }
- }
- #endregion
- #region 根据sql获取实体
- /// <summary>
- /// 根据sql获取实体
- /// </summary>
- public T FindBySql<T>(string sql) where T : new()
- {
- Type type = typeof(T);
- T result = (T)Activator.CreateInstance(type);
- IDataReader rd = null;
- bool hasValue = false;
- //获取缓存
- if (CacheHelper.Exists(type, sql))
- {
- return (T)CacheHelper.Get(type, sql);
- }
- try
- {
- rd = ExecuteReader(sql);
- PropertyInfo[] propertyInfoList = GetEntityProperties(type);
- int fcnt = rd.FieldCount;
- List<string> fileds = new List<string>();
- for (int i = ; i < fcnt; i++)
- {
- fileds.Add(rd.GetName(i).ToUpper());
- }
- while (rd.Read())
- {
- hasValue = true;
- IDataRecord record = rd;
- foreach (PropertyInfo pro in propertyInfoList)
- {
- if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
- {
- continue;
- }
- pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (rd != null && !rd.IsClosed)
- {
- rd.Close();
- rd.Dispose();
- }
- }
- if (hasValue)
- {
- CacheHelper.Add(type, sql, result);//添加缓存
- return result;
- }
- else
- {
- return default(T);
- }
- }
- #endregion
- #endregion
- #region 获取列表
- /// <summary>
- /// 获取列表
- /// </summary>
- public List<T> FindListBySql<T>(string sql) where T : new()
- {
- List<T> list = new List<T>();
- object obj;
- IDataReader rd = null;
- //获取缓存
- Type type = GetBaseType(typeof(T));
- if (CacheHelper.Exists(type, sql))
- {
- return (List<T>)CacheHelper.Get(type, sql);
- }
- try
- {
- rd = ExecuteReader(sql);
- if (typeof(T) == typeof(int))
- {
- while (rd.Read())
- {
- list.Add((T)rd[]);
- }
- }
- else if (typeof(T) == typeof(string))
- {
- while (rd.Read())
- {
- list.Add((T)rd[]);
- }
- }
- else
- {
- PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties();
- int fcnt = rd.FieldCount;
- List<string> fileds = new List<string>();
- for (int i = ; i < fcnt; i++)
- {
- fileds.Add(rd.GetName(i).ToUpper());
- }
- while (rd.Read())
- {
- IDataRecord record = rd;
- obj = new T();
- foreach (PropertyInfo pro in propertyInfoList)
- {
- if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
- {
- continue;
- }
- pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
- }
- list.Add((T)obj);
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (rd != null && !rd.IsClosed)
- {
- rd.Close();
- rd.Dispose();
- }
- }
- CacheHelper.Add(type, sql, list);//添加缓存
- return list;
- }
- #endregion
- #region 获取列表
- /// <summary>
- /// 获取列表
- /// </summary>
- public List<T> FindListBySql<T>(string sql, params MySqlParameter[] cmdParms) where T : new()
- {
- List<T> list = new List<T>();
- object obj;
- IDataReader rd = null;
- //获取缓存
- Type type = GetBaseType(typeof(T));
- if (CacheHelper.Exists(type, sql))
- {
- return (List<T>)CacheHelper.Get(type, sql);
- }
- try
- {
- rd = ExecuteReader(sql, cmdParms);
- if (typeof(T) == typeof(int))
- {
- while (rd.Read())
- {
- list.Add((T)rd[]);
- }
- }
- else if (typeof(T) == typeof(string))
- {
- while (rd.Read())
- {
- list.Add((T)rd[]);
- }
- }
- else
- {
- PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties();
- int fcnt = rd.FieldCount;
- List<string> fileds = new List<string>();
- for (int i = ; i < fcnt; i++)
- {
- fileds.Add(rd.GetName(i).ToUpper());
- }
- while (rd.Read())
- {
- IDataRecord record = rd;
- obj = new T();
- foreach (PropertyInfo pro in propertyInfoList)
- {
- if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
- {
- continue;
- }
- pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
- }
- list.Add((T)obj);
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (rd != null && !rd.IsClosed)
- {
- rd.Close();
- rd.Dispose();
- }
- }
- CacheHelper.Add(type, sql, list);//添加缓存
- return list;
- }
- #endregion
- #region 分页获取列表
- /// <summary>
- /// 分页(任意entity,尽量少的字段)
- /// </summary>
- public PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage) where T : new()
- {
- PagerModel pagerModel = new PagerModel(currentPage, pageSize);
- //获取缓存
- string cacheKey = string.Format("sql:{0},orderby:{1},pageSize:{2},currentPage:{3}", sql, orderby, pageSize, currentPage);
- Type type = GetBaseType(typeof(T));
- if (CacheHelper.Exists(type, cacheKey))
- {
- return (PagerModel)CacheHelper.Get(type, cacheKey);
- }
- using (MySqlConnection connection = new MySqlConnection(connectionString))
- {
- connection.Open();
- string commandText = string.Format("select count(*) from ({0}) T", sql);
- IDbCommand cmd = new MySqlCommand(commandText, connection);
- pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
- int startRow = pageSize * (currentPage - );
- StringBuilder sb = new StringBuilder();
- sb.Append("select * from (");
- sb.Append(sql);
- if (!string.IsNullOrWhiteSpace(orderby))
- {
- sb.Append(" ");
- sb.Append(orderby);
- }
- sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
- List<T> list = FindListBySql<T>(sb.ToString());
- pagerModel.result = list;
- }
- CacheHelper.Add(type, cacheKey, pagerModel);
- return pagerModel;
- }
- #endregion
- #region 分页获取列表
- /// <summary>
- /// 分页(任意entity,尽量少的字段)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="sql"></param>
- /// <returns></returns>
- public PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage, params MySqlParameter[] cmdParms) where T : new()
- {
- PagerModel pagerModel = new PagerModel(currentPage, pageSize);
- //获取缓存
- string cacheKey = string.Format("sql:{0},orderby:{1},pageSize:{2},currentPage:{3}", sql, orderby, pageSize, currentPage);
- Type type = GetBaseType(typeof(T));
- if (CacheHelper.Exists(type, cacheKey))
- {
- return (PagerModel)CacheHelper.Get(type, cacheKey);
- }
- using (MySqlConnection connection = new MySqlConnection(connectionString))
- {
- connection.Open();
- string commandText = string.Format("select count(*) from ({0}) T", sql);
- MySqlCommand cmd = new MySqlCommand(commandText, connection);
- PrepareCommand(cmd, connection, null, commandText, cmdParms);
- pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
- cmd.Parameters.Clear();
- int startRow = pageSize * (currentPage - );
- StringBuilder sb = new StringBuilder();
- sb.Append("select * from (");
- sb.Append(sql);
- if (!string.IsNullOrWhiteSpace(orderby))
- {
- sb.Append(" ");
- sb.Append(orderby);
- }
- sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
- List<T> list = FindListBySql<T>(sb.ToString(), cmdParms);
- pagerModel.result = list;
- }
- CacheHelper.Add(type, cacheKey, pagerModel);
- return pagerModel;
- }
- #endregion
- #region 分页获取列表
- /// <summary>
- /// 分页(任意entity,尽量少的字段)
- /// </summary>
- public DataSet FindPageBySql(string sql, string orderby, int pageSize, int currentPage, out int totalCount, params MySqlParameter[] cmdParms)
- {
- DataSet ds = null;
- //获取缓存
- string cacheKey = string.Format("sql:{0},orderby:{1},pageSize:{2},currentPage:{3}", sql, orderby, pageSize, currentPage);
- Regex reg = new Regex(@"from[\s]+([^\(\),\s]+)", RegexOptions.IgnoreCase);
- Match match = reg.Match(sql);
- string tableName = match.Groups[].Value;
- Dictionary<string, object> dic;
- if (CacheHelper.Exists(tableName, cacheKey))
- {
- dic = (Dictionary<string, object>)CacheHelper.Get(tableName, cacheKey);
- totalCount = (int)dic["totalCount"];
- return (DataSet)dic["DataSet"];
- }
- using (MySqlConnection connection = new MySqlConnection(connectionString))
- {
- connection.Open();
- string commandText = string.Format("select count(*) from ({0}) T", sql);
- IDbCommand cmd = new MySqlCommand(commandText, connection);
- totalCount = int.Parse(cmd.ExecuteScalar().ToString());
- int startRow = pageSize * (currentPage - );
- StringBuilder sb = new StringBuilder();
- sb.Append("select * from (");
- sb.Append(sql);
- if (!string.IsNullOrWhiteSpace(orderby))
- {
- sb.Append(" ");
- sb.Append(orderby);
- }
- sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
- ds = Query(sql, cmdParms);
- }
- dic = new Dictionary<string, object>();
- dic.Add("totalCount", totalCount);
- dic.Add("DataSet", ds);
- CacheHelper.Add(tableName, cacheKey, dic);
- return ds;
- }
- #endregion
- #region getReaderValue 转换数据
- /// <summary>
- /// 转换数据
- /// </summary>
- private Object getReaderValue(Object rdValue, Type ptype)
- {
- if (ptype == typeof(double))
- return Convert.ToDouble(rdValue);
- if (ptype == typeof(decimal))
- return Convert.ToDecimal(rdValue);
- if (ptype == typeof(int))
- return Convert.ToInt32(rdValue);
- if (ptype == typeof(long))
- return Convert.ToInt64(rdValue);
- if (ptype == typeof(DateTime))
- return Convert.ToDateTime(rdValue);
- if (ptype == typeof(Nullable<double>))
- return Convert.ToDouble(rdValue);
- if (ptype == typeof(Nullable<decimal>))
- return Convert.ToDecimal(rdValue);
- if (ptype == typeof(Nullable<int>))
- return Convert.ToInt32(rdValue);
- if (ptype == typeof(Nullable<long>))
- return Convert.ToInt64(rdValue);
- if (ptype == typeof(Nullable<DateTime>))
- return Convert.ToDateTime(rdValue);
- return rdValue;
- }
- #endregion
- #region 获取主键名称
- /// <summary>
- /// 获取主键名称
- /// </summary>
- public string GetIdName(Type type)
- {
- PropertyInfo[] propertyInfoList = GetEntityProperties(type);
- foreach (PropertyInfo propertyInfo in propertyInfoList)
- {
- if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute), false).Length > )
- {
- return propertyInfo.Name;
- }
- }
- return "Id";
- }
- #endregion
- #region 获取主键值
- /// <summary>
- /// 获取主键名称
- /// </summary>
- public object GetIdVal(object val)
- {
- string idName = GetIdName(val.GetType());
- if (!string.IsNullOrWhiteSpace(idName))
- {
- return val.GetType().GetProperty(idName).GetValue(val, null);
- }
- return ;
- }
- #endregion
- #region 获取实体类属性
- /// <summary>
- /// 获取实体类属性
- /// </summary>
- private PropertyInfo[] GetEntityProperties(Type type)
- {
- List<PropertyInfo> result = new List<PropertyInfo>();
- PropertyInfo[] propertyInfoList = type.GetProperties();
- foreach (PropertyInfo propertyInfo in propertyInfoList)
- {
- if (propertyInfo.GetCustomAttributes(typeof(EdmRelationshipNavigationPropertyAttribute), false).Length ==
- && propertyInfo.GetCustomAttributes(typeof(BrowsableAttribute), false).Length == )
- {
- result.Add(propertyInfo);
- }
- }
- return result.ToArray();
- }
- #endregion
- #region 获取基类
- /// <summary>
- /// 获取基类
- /// </summary>
- public Type GetBaseType(Type type)
- {
- while (type.BaseType != null && type.BaseType.Name != typeof(Object).Name)
- {
- type = type.BaseType;
- }
- return type;
- }
- #endregion
- #endregion
- #region 事务
- #region 开始事务
- /// <summary>
- /// 开始事务
- /// </summary>
- public static void BeginTransaction()
- {
- GetTran();
- AddTranFlag();
- }
- #endregion
- #region 提交事务
- /// <summary>
- /// 提交事务
- /// </summary>
- public static void CommitTransaction()
- {
- try
- {
- if (GetConn().State == ConnectionState.Open)
- {
- GetTran().Commit();
- RemoveTranFlag();
- }
- }
- catch (Exception ex)
- {
- GetTran().Rollback();
- RemoveTranFlag();
- }
- finally
- {
- if (GetConn().State == ConnectionState.Open) GetConn().Close();
- }
- }
- #endregion
- #region 回滚事务(出错时调用该方法回滚)
- /// <summary>
- /// 回滚事务(出错时调用该方法回滚)
- /// </summary>
- public static void RollbackTransaction()
- {
- GetTran().Rollback();
- RemoveTranFlag();
- GetConn().Close();
- }
- #endregion
- #endregion
- }
- }
CacheHelper代码:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Configuration;
- using System.Data;
- using System.Data.Objects.DataClasses;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Web;
- using System.Web.Caching;
- namespace DBHelper
- {
- /// <summary>
- /// 缓存类
- /// </summary>
- public static class CacheHelper
- {
- #region 变量
- /// <summary>
- /// 缓存整个页面的键
- /// </summary>
- public static string pageCacheKey = "pageCacheKey";
- #endregion
- #region 是否存在
- /// <summary>
- /// 是否存在
- /// </summary>
- public static bool Exists<T>(string key)
- {
- return Exists(typeof(T).Name, key);
- }
- /// <summary>
- /// 是否存在
- /// </summary>
- public static bool Exists(Type type, string key)
- {
- return Exists(type.Name, key);
- }
- /// <summary>
- /// 是否存在
- /// </summary>
- public static bool Exists(string tableName, string key)
- {
- return false; //禁用缓存
- if (HttpRuntime.Cache[tableName] != null)
- {
- Dictionary<string, object> dic = (Dictionary<string, object>)HttpRuntime.Cache[tableName];
- if (dic.Keys.Contains<string>(key))
- {
- return true;
- }
- }
- return false;
- }
- #endregion
- #region 添加缓存
- /// <summary>
- /// 添加缓存
- /// </summary>
- public static void Add<T>(string key, object value)
- {
- Add(typeof(T).Name, key, value);
- }
- /// <summary>
- /// 添加缓存
- /// </summary>
- public static void Add(Type type, string key, object value)
- {
- Add(type.Name, key, value);
- }
- /// <summary>
- /// 添加缓存
- /// </summary>
- public static void Add(string tableName, string key, object value)
- {
- return; //禁用缓存
- if (HttpRuntime.Cache[tableName] == null)
- {
- Dictionary<string, object> dic = new Dictionary<string, object>();
- dic.Add(key, value);
- HttpRuntime.Cache.Insert(tableName, dic);
- }
- else
- {
- Dictionary<string, object> dic = (Dictionary<string, object>)HttpRuntime.Cache[tableName];
- if (dic.Keys.Contains<string>(key))
- {
- dic[key] = value;
- }
- else
- {
- dic.Add(key, value);
- }
- HttpRuntime.Cache[tableName] = dic;
- }
- }
- #endregion
- #region 获取缓存
- /// <summary>
- /// 获取缓存
- /// </summary>
- public static object Get<T>(string key)
- {
- return Get(typeof(T).Name, key);
- }
- /// <summary>
- /// 获取缓存
- /// </summary>
- public static object Get(Type type, string key)
- {
- return Get(type.Name, key);
- }
- /// <summary>
- /// 获取缓存
- /// </summary>
- public static object Get(string tableName, string key)
- {
- return null; //禁用缓存
- if (HttpRuntime.Cache[tableName] != null)
- {
- Dictionary<string, object> dic = (Dictionary<string, object>)HttpRuntime.Cache[tableName];
- if (dic.Keys.Contains<string>(key))
- {
- return dic[key];
- }
- }
- return null;
- }
- #endregion
- #region 删除缓存
- /// <summary>
- /// 删除所有缓存
- /// </summary>
- public static void Clear()
- {
- return; //禁用缓存
- string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
- int start = connectionString.IndexOf("database=") + ;
- int end = connectionString.IndexOf("user id=");
- string owner = connectionString.Substring(start, end - start).Replace(";", "").ToUpper();
- MySqlHelper dbHelper = new MySqlHelper();
- DataTable dt = dbHelper.Query(string.Format(@"
- SELECT TABLE_NAME as TABLE_NAME,TABLE_COMMENT as COMMENTS
- FROM INFORMATION_SCHEMA.TABLES
- WHERE TABLE_SCHEMA = '{0}'", owner)).Tables[];
- foreach (DataRow dr in dt.Rows)
- {
- HttpRuntime.Cache.Remove(dr["TABLE_NAME"].ToString());
- HttpRuntime.Cache.Remove(dr["TABLE_NAME"].ToString() + "_ext");
- }
- HttpRuntime.Cache.Remove(pageCacheKey);
- }
- /// <summary>
- /// 删除缓存
- /// </summary>
- public static void Remove<T>()
- {
- Remove(typeof(T).Name);
- }
- /// <summary>
- /// 删除缓存
- /// </summary>
- public static void Remove(Type type)
- {
- Remove(type.Name);
- }
- /// <summary>
- /// 删除缓存
- /// </summary>
- public static void Remove(string tableName)
- {
- return; //禁用缓存
- HttpRuntime.Cache.Remove(tableName);
- HttpRuntime.Cache.Remove(tableName + "_ext");
- HttpRuntime.Cache.Remove(pageCacheKey);
- }
- #endregion
- }
- }
添加、修改、删除操作十分简捷方便,分别只需要一行代码。在并发量很小的情况下,可以通过GetMaxID方法生产新的ID,否则请采用其它方法。代码如下:
- #region 添加
- /// <summary>
- /// 添加
- /// </summary>
- public void Insert(cms_content model)
- {
- model.id = dbHelper.GetMaxID<cms_content>("id");
- dbHelper.Insert(model);
- }
- #endregion
- #region 修改
- /// <summary>
- /// 修改
- /// </summary>
- public void Update(cms_content model)
- {
- dbHelper.Update(model);
- }
- #endregion
- #region 删除
- /// <summary>
- /// 删除
- /// </summary>
- public void Del(string ids)
- {
- dbHelper.BatchDelete<cms_content>(ids);
- }
- #endregion
查询单个实体也非常方便,可以用ID查询,也可以写原生sql语句查询,十分灵活。代码如下:
- /// <summary>
- /// 获取
- /// </summary>
- public cms_content Get(int id)
- {
- return dbHelper.FindById<cms_content>(id.ToString());
- }
- /// <summary>
- /// 根据channelId获取一条内容详情
- /// </summary>
- public cms_content GetByChannelId(int channelId)
- {
- return dbHelper.FindBySql<cms_content>(string.Format("select * from cms_content where channelId={0} and audit=1", channelId));
- }
查询获取集合使用原生sql语句,非常灵活方便,你可以写非常非常复杂的sql语句,各种join,各种子查询,都可以。代码如下:
- /// <summary>
- /// 获取列表
- /// </summary>
- public List<cms_content_ext> GetList(ref PagerModel pager, int channelId, string title, int audit)
- {
- StringBuilder sql = new StringBuilder(string.Format(@"
- select content.*, channel.title as channelName, user.showName
- from cms_content content
- left join cms_channel channel on channel.id=content.channelId
- left join sys_user user on user.id=content.publishUserId
- where 1=1 "));
- if (channelId != -)
- {
- sql.AppendFormat(" and content.channelId = {0}", channelId);
- }
- if (!string.IsNullOrWhiteSpace(title))
- {
- sql.AppendFormat(" and content.title like '%{0}%'", title);
- }
- if (audit != -)
- {
- sql.AppendFormat(" and content.audit = {0}", audit);
- }
- string orderby = string.Format("order by content.publishTime desc,id desc");
- PagerModel pagerModel = dbHelper.FindPageBySql<cms_content_ext>(sql.ToString(), orderby, pager.rows, pager.page);
- pager.totalRows = pagerModel.totalRows;
- pager.result = pagerModel.result;
- return pagerModel.result as List<cms_content_ext>;
- }
MySqlHelper、CacheHelper的更多相关文章
- WebHelper-SessionHelper、CookieHelper、CacheHelper、Tree
ylbtech-Unitity: cs-WebHelper-SessionHelper.CookieHelper.CacheHelper.Tree SessionHelper.cs CookieHel ...
- C# WebHelper-CookieHelper,CacheHelper,SessionHelper
常用web操作工具类,记录一下,本文记录的工具类,都要求引用 System.Web 1.CookieHelper /// <summary> /// Cookie工具类 /// </ ...
- Dos.Common - 目录、介绍
引言: Dos.Common是一个开发中的常用类库,如HttpHelper.LogHelper.CacheHelper.CookieHelper.MapperHelper等等.与Dos.WeChat. ...
- Dos.Common
引言: Dos.Common是一个开发中的常用类库,如HttpHelper.LogHelper.CacheHelper.CookieHelper.MapperHelper等等.与Dos.WeChat. ...
- 话说C#程序员人手一个ORM
话说C#程序员人手一个ORM,确实没有必要再写ORM了,不过我的ORM并不是新的,是从DBHelper演化过来的,算是DBHelper魔改版. 目前流行的ORM有EF.Dapper.SqlSugar. ...
- java操作MySQL数据库(插入、删除、修改、查询、获取所有行数)
插播一段广告哈:我之前共享了两个自己写的小应用,见这篇博客百度地图开发的两个应用源码共享(Android版),没 想到有人找我来做毕设了,年前交付,时间不是很紧,大概了解了下就接下了,主要用到的就是和 ...
- 对依赖倒置原则(DIP)及Ioc、DI、Ioc容器的一些理解
1.概述 所谓依赖倒置原则(Dependence Inversion Principle)就是要依赖于抽象,不要依赖于具体.简单的说就是要求对抽象进行编程,不要对实现进行编程,这样就降低了客户与实现模 ...
- 十二、EnterpriseFrameWork框架核心类库之与EntLib结合
从本章开始对框架的讲叙开始进入核心类库的讲解,前面都是对框架外在功能讲解,让人有个整体的概念,知道包含哪些功能与对系统开发有什么帮助.以后多章都是讲解核心类库的,讲解的方式基本按照代码的目录结构,这样 ...
- PostgreSQL和Greenplum、Npgsql
PostgreSQL和Greenplum.Npgsql 想着要不要写,两个原因“懒”和“空”.其实懒和空也是有联系的,不是因为懒的写,而是因为对PostgreSQL和Npgsql的知识了解匮乏,也就懒 ...
随机推荐
- CSS Font知识整理总结
1.什么是字体 字体是文字的外在形式,就是文字的风格,是文字的外衣.比如行书.楷书.草书,都是一种字体.同样一个字每个人写起来都会有差异,可以说每个人都有一套潜在的字体库.对于web页面来说,字体就是 ...
- [.net 面向对象编程基础] (5) 基础中的基础——变量和常量
[.net面向对象编程基础] (5) 基础中的基础——变量和常量 1.常量:在编译时其值能够确定,并且程序运行过程中值不发生变化的量. 通俗来说,就是定义一个不能改变值的量.既然不能变动值,那就必须 ...
- http学习笔记(一)
写在前面: 第一次想写系列文章,学习了一些web知识后,发现自己还有很大的不足,但又不知道该学习些什么来完善自己的知识体系,偶然在网上看到了一篇介绍http的文章,觉得对自己有一些帮助,于是想要开始学 ...
- 12小时包你学会基于ReactMix框架的ReactNativeApp开发(二)基于Css+HTML写第一个app页面
上一篇文章,大家对于ReactMix(https://github.com/xueduany/react-mix)框架有了一个基本认识,知道我们是一个语法糖,帮助大家基于一套代码,所有平台都能跑.那么 ...
- 将网站添加到iPhone的主屏幕上
我之前有篇文章介绍过如何将网站固定到Windows的开始菜单,并可以自定义图标.颜色以及Windows推送通知,其实Apple也有类似的功能,通过在网页的head部分添加link标记,在Safari浏 ...
- MySQL 5.7新特性之Generated Column(函数索引)
MySQL 5.7引入了Generated Column,这篇文章简单地介绍了Generated Column的使用方法和注意事项,为读者了解MySQL 5.7提供一个快速的.完整的教程.这篇文章围绕 ...
- JSONP浅析
DEMO : JSONP示例 为什么使用JSONP JSONP和JSON是不一样的.JSON(JavaScript Object Notation)是一种基于文本的数据交换方式,或者叫做数据描述格式. ...
- java基础-继承:矩形体积类问题
28.按要求编写一个Java应用程序: (1)定义一个类,描述一个矩形,包含有长.宽两种属性,和计算面积方法. (2)编写一个类,继承自矩形类,同时该类描述长方体,具有长.宽.高属性, 和计算体积的方 ...
- PHP将富文本编辑后的内容,去除样式图片等只保留txt文本内容
1.从数据库读取富文本内容样式如下: <p style=";text-indent: 0;padding: 0;line-height: 26px"><span ...
- png图片制作任意颜色的小图标
本内容只要是对张鑫旭PNG格式小图标的CSS任意颜色赋色技术的这篇文章进行详细说明. HTML: <i class="icon"><i class="i ...