微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MySqlHelper、CacheHelper

MysqLHelper代码

using System;
 System.Collections;
 System.Collections.Generic;
 System.ComponentModel;
 System.Configuration;
 System.Data;
 MysqL.Data.MysqLClient;
 System.Linq;
 System.Reflection;
 System.Text;
 System.Web;
 System.Xml.Linq;
 System.Data.Objects.DataClasses;
 Models;
 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 获取数据库连接
         获取数据库连接
        static MysqLConnection GetConn()
        {
            MysqLConnection connection = null;

            string key = Simpo2016_MysqLConnectionif (HttpContext.Current.Items[key] == )
            {
                connection = new MysqLConnection(connectionString);
                connection.open();
                HttpContext.Current.Items[key] = connection;
            }
            else
            {
                connection = (MysqLConnection)HttpContext.Current.Items[key];
            }

            return connection;
        }
        #region MysqLTransaction 获取事务对象
         获取事务对象
         MysqLTransaction GetTran()
        {
            MysqLTransaction tran = Simpo2016_MysqLTransaction)
            {
                tran = GetConn().BeginTransaction();
                HttpContext.Current.Items[key] = tran;
            }
            
            {
                tran = (MysqLTransaction)HttpContext.Current.Items[key];
            }

             tran;
        }
        #region 开起事务标志
         事务标志
        string tranFlagKey = Simpo2016_MysqLTransaction_Flag;
         添加事务标志
        void AddTranFlag()
        {
            HttpContext.Current.Items[tranFlagKey] = true;
        }
         移除事务标志
         RemoveTranFlag()
        {
            HttpContext.Current.Items[tranFlagKey] = falsebool TranFlag
        {
            get
            {
                bool tranFlag = ;

                if (HttpContext.Current.Items[tranFlagKey] != )
                {
                    tranFlag = ()HttpContext.Current.Items[tranFlagKey];
                }

                 tranFlag;
            }
        }
        #region 用于查询数据库连接
         用于查询数据库连接
        private MysqLConnection m_Conn;
        #region 构造函数
        public MysqLHelper()
        {
            m_Conn =  MysqLConnection(connectionString);
        }
        #region 基础方法
        #region  执行简单sql语句
        #region Exists
        bool Exists(string sqlString)
        {
            using (MysqLCommand cmd =  MysqLCommand(sqlString,m_Conn))
            {
                try
                {
                    m_Conn.open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj,null)) || (Object.Equals(obj,System.dbnull.Value)))
                    {
                        return ;
                    }
                    
                    {
                        ;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cmd.dispose();
                    m_Conn.Close();
                }
            }
        }
        #region 执行sql语句,返回影响的记录数
         执行sql语句,返回影响的记录数
        </summary>
        <param name="sqlString">sql语句</param>
        <returns>影响的记录数</returns>
        int Executesql( sqlString)
        {
            MysqLConnection connection = GetConn();
            
                {
                    if (connection.State != ConnectionState.Open) connection.open();
                    if (TranFlag) cmd.Transaction = GetTran();
                    int rows = cmd.ExecuteNonQuery();
                     rows;
                }
                throw  Exception(ex.Message);
                }
                
                {
                    cmd.dispose();
                    if (!TranFlag) connection.Close();
                }
            }
        }
        #region 执行一条计算查询结果语句,返回查询结果
         执行一条计算查询结果语句,返回查询结果(object)
        计算查询结果语句查询结果(object)object GetSingle( obj;
                    }
                }
                #region 执行查询语句,返回sqliteDataReader
         执行查询语句,返回sqliteDataReader ( 注意:调用方法后,一定要对sqlDataReader进行Close )
        查询语句sqliteDataReaderpublic MysqLDataReader ExecuteReader( sqlString)
        {
            MysqLConnection connection =  MysqLConnection(connectionString);
            MysqLCommand cmd = 
            {
                connection.open();
                MysqLDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                 myReader;
            }
             (Exception ex)
            {
                 ex;
            }
        }
        #region 执行查询语句,返回DataSet
         执行查询语句,返回DataSet
        DataSetpublic DataSet Query(using (MysqLConnection connection =  MysqLConnection(connectionString))
            {
                DataSet ds =  DataSet();
                
                {
                    connection.open();
                    MysqLDataAdapter command =  MysqLDataAdapter(sqlString,connection);
                    command.Fill(ds,ds);
                }
                
                {
                    connection.Close();
                }
                 ds;
            }
        }
        #endregion
        #region 执行带参数的sql语句
        <param name="sqlString">string sqlString,1)">params MysqLParameter[] cmdParms)
        {
            MysqLConnection connection = MysqLCommand())
            {
                
                {
                    PrepareCommand(cmd,connection,,sqlString,cmdParms);
                     cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    <param name="strsql">string sqlString,1)"> MysqLParameter[] cmdParms)
        {
            MysqLCommand cmd =  MysqLCommand();
            
            {
                PrepareCommand(cmd,m_Conn,sqlString,cmdParms);
                MysqLDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                 ex;
            }

        }
         MysqLCommand();
            PrepareCommand(cmd,cmdParms);
            using (MysqLDataAdapter da =  MysqLDataAdapter(cmd))
            {
                DataSet ds = 
                {
                    da.Fill(ds,1)">);
                    cmd.Parameters.Clear();
                }
                
                {
                    cmd.dispose();
                    m_Conn.Close();
                }
                #region PrepareCommand
        void PrepareCommand(MysqLCommand cmd,MysqLConnection conn,MysqLTransaction trans,1)"> 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 != )
            {
                foreach (MysqLParameter parm in cmdParms)
                {
                    cmd.Parameters.Add(parm);
                }
            }
        }
        #region 增删改查
        #region 获取最大编号
         获取最大编号
        <typeparam name="T">实体Model</typeparam>
        <param name="key">主键</param>
        int GetMaxID<T>( key)
        {
            Type type = typeof(T);

            string sql = string.Format(SELECT Max({0}) FROM {1} MysqLCommand(sql,1)">return 1int.Parse(obj.ToString()) + #region 添加
         添加
        void Insert(object obj)
        {
            StringBuilder strsql =  StringBuilder();
            Type type = obj.GetType();
            CacheHelper.Remove(type);//删除缓存
            strsql.Append(insert into {0}( GetEntityProperties(type);
            List<string> propertyNameList = new List<string>();
            foreach (PropertyInfo propertyInfo  propertyInfoList)
            {
                propertyNameList.Add(propertyInfo.Name);
            }

            strsql.Append({0})",1)">string.Join(sql.Append( values ({0})string>(a => @" + a).ToArray())));
            MysqLParameter[] parameters =  MysqLParameter[propertyInfoList.Length];
            for (int i = 0; i < propertyInfoList.Length; i++)
            {
                PropertyInfo propertyInfo = propertyInfoList[i];
                object val = propertyInfo.GetValue(obj,1)">);
                MysqLParameter param = new MysqLParameter(" + propertyInfo.Name,val == null ? dbnull.Value : val);
                parameters[i] = param;
            }

            Executesql(strsql.ToString(),parameters);
        }
        #region 修改
         修改
        void Update( obj)
        {
            object oldobj = Find(obj,1)">);
            if (oldobj == null) new Exception(无法获取到旧数据);

            StringBuilder strsql = update {0} int savedCount = 0;
             propertyInfoList)
            {
                object oldVal = propertyInfo.GetValue(oldobj,1)">);
                .Equals(oldVal,val))
                {
                    propertyNameList.Add(propertyInfo.Name);
                    savedCount++;
                }
            }

            strsql.Append( set ));
            MysqLParameter[] parameters =  MysqLParameter[savedCount];
            StringBuilder sbPros =  StringBuilder();
            int k =  {0}=@{0},propertyInfo.Name));
                    MysqLParameter param =  dbnull.Value : val);
                    parameters[k++] = param;
                }
            }
            if (sbPros.Length > )
            {
                strsql.Append(sbPros.ToString(0,sbPros.Length - ));
            }
            strsql.Append( where {0}='{1}'if (savedCount > )
            {
                Executesql(strsql.ToString(),parameters);
            }
        }
        #region 删除
         根据Id删除
        void Delete<T>(int id)
        {
            Type type = (T);
            CacheHelper.Remove(type);删除缓存
            StringBuilder sbsql =  StringBuilder();
            sbsql.Append(delete from {0} where {2}='{1}'sql(sbsql.ToString());
        }
         根据Id集合删除
        void BatchDelete<T>( ids)
        {
            if (string.IsNullOrWhiteSpace(ids)) ;

            Type type = delete from {0} where {2} in ({1}) 根据条件删除
         conditions)
        {
            string.IsNullOrWhiteSpace(conditions)) delete from {0} where {1}sql(sbsql.ToString());
        }
        #region 获取实体
        #region 根据实体获取实体
         根据实体获取实体
        object Find(object obj,1)">bool readCache = )
        {
            Type type = obj.GetType();

            object result = Activator.CreateInstance(type);
            bool hasValue = ;
            IDataReader rd = select * from {0} where {2}='{1}'获取缓存
            if (readCache && CacheHelper.Exists(type,sql))
            {
                 CacheHelper.Get(type,sql);
            }

            
            {
                rd = ExecuteReader(sql);

                PropertyInfo[] propertyInfoList = GetEntityProperties(type);

                int fcnt = rd.FieldCount;
                List<string> fileds = ();
                0; i < fcnt; i++)
                {
                    fileds.Add(rd.GetName(i).toupper());
                }

                while (rd.Read())
                {
                    hasValue = ;
                    IDataRecord record = rd;

                    foreach (PropertyInfo pro  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),1)">);
                    }
                }
            }
             ex;
            }
            if (rd != null && !rd.IsClosed)
                {
                    rd.Close();
                    rd.dispose();
                }
            }

            if (hasValue)
            {
                CacheHelper.Add(type,sql,result);添加缓存
                 result;
            }
            ;
            }
        }
        #region 根据Id获取实体
         根据Id获取实体
        object FindById(Type type,1)"> id)
        {
             Activator.CreateInstance(type);
            IDataReader rd =  (CacheHelper.Exists(type,1)">public T FindById<T>(string id) where T : ()
        {
            Type type = (T);
            T result = (T)Activator.CreateInstance(type);
            IDataReader rd =  (T)CacheHelper.Get(type,1)">default(T);
            }
        }
        #region 根据sql获取实体
         根据sql获取实体
        public T FindBysql<T>(string sql) #region 获取列表
         获取列表
        public List<T> FindListBysql<T>(()
        {
            List<T> list = new List<T> obj;
            IDataReader rd = 获取缓存
            Type type = GetBaseType((T));
            return (List<T>)CacheHelper.Get(type,1)"> ExecuteReader(sql);

                typeof(T) == typeof())
                {
                     (rd.Read())
                    {
                        list.Add((T)rd[]);
                    }
                }
                else 
                {
                    PropertyInfo[] propertyInfoList = ((T)).GetProperties();

                     rd.FieldCount;
                    List<();
                    )
                    {
                        fileds.Add(rd.GetName(i).toupper());
                    }

                     (rd.Read())
                    {
                        IDataRecord record = rd;
                        obj =  T();


                         propertyInfoList)
                        {
                             dbnull.Value)
                            {
                                ;
                            }

                            pro.SetValue(obj,1)">);
                        }
                        list.Add((T)obj);
                    }
                }
            }
            rd.IsClosed)
                {
                    rd.Close();
                    rd.dispose();
                }
            }

            CacheHelper.Add(type,list);添加缓存
             list;
        }
        string sql,1)">params MysqLParameter[] cmdParms)  ExecuteReader(sql,cmdParms);

                #region 分页获取列表
         分页(任意entity,尽量少的字段)
        public PagerModel FindPageBysql<T>(string orderby,1)">int pageSize,1)">int currentPage) ()
        {
            PagerModel pagerModel =  PagerModel(currentPage,pageSize);

            string cacheKey = sql:{0},orderby:{1},pageSize:{2},currentPage:{3}orderby (PagerModel)CacheHelper.Get(type,cacheKey);
            }

             MysqLConnection(connectionString))
            {
                connection.open();
                string commandText = select count(*) from ({0}) Tsql);
                IDbCommand cmd =  MysqLCommand(commandText,connection);
                pagerModel.totalRows = .Parse(cmd.ExecuteScalar().ToString());

                int startRow = pageSize * (currentPage - );

                StringBuilder sb =  StringBuilder();
                sb.Append(select * from ();
                sb.Append(sql);
                string.IsNullOrWhiteSpace())
                {
                    sb.Append(" );
                    sb.Append();
                }
                sb.AppendFormat( ) row_limit limit {0},{1}sql<T>(sb.ToString());
                pagerModel.result = list;
            }

            CacheHelper.Add(type,cacheKey,pagerModel);
             pagerModel;
        }
        <typeparam name="T"></typeparam>
        <param name="sql"></param>
        <returns></returns>
        int currentPage,sql);
                MysqLCommand cmd = .Parse(cmd.ExecuteScalar().ToString());
                cmd.Parameters.Clear();

                (sb.ToString(),cmdParms);
                pagerModel.result = pagerModel;
        }


        public DataSet FindPageBysql(out int totalCount,1)"> MysqLParameter[] cmdParms)
        {
            DataSet ds = new Regex(@"from[\s]+([^\(\),\s]+)noreCase);
            Match match = reg.Match(sql);
            string tableName = match.Groups[].Value;
            Dictionary<string,1)">object> dic;
             (CacheHelper.Exists(tableName,cacheKey))
            {
                dic = (Dictionary<)CacheHelper.Get(tableName,cacheKey);
                totalCount = (int)dic[totalCount];
                return (DataSet)dic[];
            }

            = Query(sql,cmdParms);
            }

            dic = new Dictionary<();
            dic.Add( ds;
        }
        #region getReaderValue 转换数据
         转换数据
         Object getReaderValue(Object rdValue,Type ptype)
        {
            if (ptype == double))
                 Convert.Todouble(rdValue);

            decimal Convert.ToDecimal(rdValue);

             Convert.ToInt32(rdValue);

            long Convert.ToInt64(rdValue);

            (DateTime))
                 Convert.ToDateTime(rdValue);

            typeof(Nullable<double>decimal>int>long>typeof(Nullable<DateTime> rdValue;
        }
        #region 获取主键名称
         获取主键名称
         GetIdName(Type type)
        {
            PropertyInfo[] propertyInfoList = GetEntityProperties(type);
            if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute),1)">false).Length > )
                {
                     propertyInfo.Name;
                }
            }
            Id;
        }
        #region 获取主键值
        object GetIdVal( val)
        {
            string idName = GetIdName(val.GetType());
            .IsNullOrWhiteSpace(idName))
            {
                return val.GetType().GetProperty(idName).GetValue(val,1)">);
            }
            #region 获取实体类属性
         获取实体类属性
         PropertyInfo[] GetEntityProperties(Type type)
        {
            List<PropertyInfo> result = new List<PropertyInfo>();
            PropertyInfo[] propertyInfoList = type.GetProperties();
            typeof(EdmRelationshipNavigationPropertyAttribute),1)">false).Length == 0
                    && propertyInfo.GetCustomAttributes(typeof(browsableAttribute),1)">)
                {
                    result.Add(propertyInfo);
                }
            }
             result.ToArray();
        }
        #region 获取基类
         获取基类
         Type GetBaseType(Type type)
        {
            while (type.BaseType != null && type.BaseType.Name != (Object).Name)
            {
                type = type.BaseType;
            }
             type;
        }
        #region 事务
        #region 开始事务
         开始事务
         BeginTransaction()
        {
            GetTran();
            AddTranFlag();
        }
        #region 提交事务
         提交事务
         CommitTransaction()
        {
            if (GetConn().State == ConnectionState.Open)
                {
                    GetTran().Commit();
                    RemoveTranFlag();
                }
            }
             (Exception ex)
            {
                GetTran().Rollback();
                RemoveTranFlag();
            }
             ConnectionState.Open) GetConn().Close();
            }
        }
        #region 回滚事务(出错时调用方法回滚)
         回滚事务(出错时调用方法回滚)
         RollbackTransaction()
        {
            GetTran().Rollback();
            RemoveTranFlag();
            GetConn().Close();
        }
        #endregion

    }
}
View Code

CacheHelper代码

 System.Web.Caching;

 缓存类
     CacheHelper
    {
        #region 变量
         缓存整个页面的键
        string pageCacheKey = pageCacheKey;
        #region 是否存在
         是否存在
        bool Exists<T>( key)
        {
            return Exists((T).Name,key);
        }
        bool Exists(Type type,1)"> Exists(type.Name,1)">string tableName,1)">false; 禁用缓存
            if (httpruntime.cache[tableName] != )
            {
                Dictionary<object> dic = (Dictionary<)httpruntime.cache[tableName];
                if (dic.Keys.Contains<(key))
                {
                    ;
                }
            }
            #region 添加缓存
         添加缓存
        void Add<T>(string key,1)"> value)
        {
            Add(void Add(Type type,1)"> value)
        {
            Add(type.Name,1)">void Add( value)
        {
            return; if (httpruntime.cache[tableName] == object> dic = ();
                dic.Add(key,value);
                httpruntime.cache.Insert(tableName,dic);
            }
            
            {
                Dictionary<(key))
                {
                    dic[key] = value;
                }
                
                {
                    dic.Add(key,value);
                }
                httpruntime.cache[tableName] = dic;
            }
        }
        #region 获取缓存
         获取缓存
        object Get<T>(return Get(object Get(Type type,1)"> Get(type.Name,1)">object Get(null;  dic[key];
                }
            }
            #region 删除缓存
         删除所有缓存
         Clear()
        {
            ].ToString();
            int start = connectionString.IndexOf(database=") + 9int end = connectionString.IndexOf(user id=string owner = connectionString.Substring(start,end - start).Replace(;"").toupper();
            MysqLHelper dbHelper =  MysqLHelper();
            DataTable dt = dbHelper.Query(
                SELECT TABLE_NAME as TABLE_NAME,TABLE_COMMENT as COMMENTS 
                FROM @R_616_4045@ION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = '{0}'];
            foreach (DaTarow dr  dt.Rows)
            {
                httpruntime.cache.Remove(dr[TABLE_NAME].ToString());
                httpruntime.cache.Remove(dr["].ToString() + _ext);
            }
            httpruntime.cache.Remove(pageCacheKey);
        }
         删除缓存
        void Remove<T>()
        {
            Remove((T).Name);
        }
         Remove(Type type)
        {
            Remove(type.Name);
        }
        void Remove( tableName)
        {
            禁用缓存
            httpruntime.cache.Remove(tableName);
            httpruntime.cache.Remove(tableName + );
            httpruntime.cache.Remove(pageCacheKey);
        }
        

    }
}
View Code

    添加修改删除操作十分简捷方便,分别只需要一行代码并发量很小的情况下,可以通过GetMaxID方法生产新的ID,否则请采用其它方法代码如下:

#region 添加
<summary>
 添加
</summary>
 Insert(cms_content model)
{
    model.id = dbHelper.GetMaxID<cms_content>(id);
    dbHelper.Insert(model);
}
#endregion

#region 修改
 修改
 Update(cms_content model)
{
    dbHelper.Update(model);
}
#region 删除
 删除
void Del( ids)
{
    dbHelper.BatchDelete<cms_content>(ids);
}
#endregion
View Code

    查询单个实体也非常方便,可以用ID查询,也可以写原生sql语句查询,十分灵活。代码如下:

 获取
public cms_content Get( id)
{
    return dbHelper.FindById<cms_content>(id.ToString());
}
 根据channelId获取一条内容详情
public cms_content GetByChannelId( channelId)
{
    return dbHelper.FindBysql<cms_content>(select * from cms_content where channelId={0} and audit=1View Code

    查询获取集合使用原生sql语句,非常灵活方便,你可以写非常非常复杂的sql语句,各种join,各种子查询,都可以。代码如下:

 获取列表
public List<cms_content_ext> GetList(ref PagerModel pager,1)">int channelId,1)">string title,1)"> audit)
{
    StringBuilder sql = new StringBuilder(
        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}.IsNullOrWhiteSpace(title))
    {
        sql.AppendFormat( and content.title like '%{0}%'if (audit != - and content.audit = {0}orderby = order by content.publishTime desc,id desc);
    PagerModel pagerModel = dbHelper.FindPageBysql<cms_content_ext>(sql.ToString(),pager.rows,pager.page);
    pager.totalRows = pagerModel.totalRows;
    pager.result = pagerModel.result;
    return pagerModel.result as List<cms_content_ext>;
}
View Code

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐