基类

/*

 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;

namespace Moon.Orm
{
    /// <summary>
    /// Description of Db.
    /// </summary>
    public class Db:IDisposable
    {
        
        /// <summary>
        /// 默认构造
        /// </summary>
        public Db()
        {
        }
        static Assembly _assembly;
        static string  _DefaultDbConnectionString;
        static string _FullTypeName;
        static string _DLLName;
        static object _lock=new object();
        public static Db CreateDefaultDb(){
            lock(_lock){
                if (_DefaultDbConnectionString==null) {
                    var config=ConfigurationManager.ConnectionStrings["DefaultConnection"];
                    var providerName=config.ProviderName;
                    string[] arra=providerName.Split(',');
                    _DLLName=arra[0]+".dll";
                    _FullTypeName=arra[1];
                    _DefaultDbConnectionString=config.ConnectionString;
                }
            }
            
            if (_DLLName=="Moon.Orm.dll") {
                if (_FullTypeName=="Moon.Orm.SqlServer") {
                    return new SqlServer(_DefaultDbConnectionString);
                }
                else if (_FullTypeName=="Moon.Orm.MySql") {
                    return new MySql(_DefaultDbConnectionString);
                }
                Type tp = Type.GetType(_FullTypeName);
                object[] constructParms = new object[] { _DefaultDbConnectionString };
                var ret= Activator.CreateInstance(tp, constructParms) as Db;
                return ret;
            }else{
                if (_assembly==null) {
                    _assembly=Assembly.LoadFrom(_DLLName);
                }
                Type tp=_assembly.GetType(_FullTypeName);
                object[] constructParms = new object[] { _DefaultDbConnectionString };
                var ret= Activator.CreateInstance(tp, constructParms) as Db;
                return ret;
            }
        }
        /// <summary>
        /// 通过连接字符串构造
        /// </summary>
        /// <param name="linkString"></param>
        public Db(string linkString)
        {
            this.LinkString=linkString;
        }
        public DbAdoMethod AdoMethod{
            get;
            set;
        }
        /// <summary>
        /// 参数化查询的标记 @、:
        /// </summary>
        protected string PName{
            get;
            set;
        }
        /// <summary>
        /// 连接字符串
        /// </summary>
        public string LinkString{
            get;
            set;
        }
        /// <summary>
        /// 当前的调试字符串,如果DebugEnabled=false,数据为空
        /// </summary>
        public string CurrentSQL{
            get;
            set;
        }
        /// <summary>
        /// 启动调试否
        /// </summary>
        public bool DebugEnabled{
            get;
            set;
        }
        /// <summary>
        /// db连接
        /// </summary>
        public DbConnection Connection{
            get;
            set;
        }
        /// <summary>
        /// 事务
        /// </summary>
        public DbTransaction Transaction{
            get;
            set;
        }
        private bool _transactionEnabled;
        /// <summary>
        /// 是否启动事务功能
        /// </summary>
        public bool TransactionEnabled{
            get{
                return _transactionEnabled;
            }
            set{
                _transactionEnabled=value;
                if (value) {
                    this.Transaction=Connection.BeginTransaction();
                }
            }
        }
        
        /// <summary>
        /// 获取删除所用的sql
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public StringBuilder GetRemoveParametersSQL(WhereExpression expression){
            string tableName=expression.WhereContent.Split('.')[0];
            string sql="delete from  "+tableName+" where "+expression.WhereContent;
            StringBuilder retSB = new StringBuilder ();
            int index = 1;
            for (int i=0; i<sql.Length; i++) {
                Char c=sql [i];
                if ('@' == c) {
                    retSB.Append (this.PName+"p" + index);
                    index++;
                } else {
                    retSB.Append (c);
                }
            }
            return retSB;
        }
        /// <summary>
        /// 获取更新所用的sql
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public StringBuilder GetUpdateSQL(EntityBase entity){
            Dictionary<string,object> all=entity.ChangedMap;
            var attributes=entity.GetType().GetCustomAttributes(true);
            string tableName=string.Empty;
            if(attributes.Length>0)
            {
                TableAttribute table=attributes[0as TableAttribute;
                if (table==null) {
                    table=attributes[1as TableAttribute;
                }
                tableName=table.TableName;
            }
            else
            {
                throw new Exception("实体类的没有table标记");
            }
            StringBuilder sb=new StringBuilder();
            //
            
            sb.Append("update "+tableName+" set ");
            int index=0;
            
            foreach (KeyValuePair<string,object> field in all) {
                index++;
                if (index==all.Count) {
                    sb.Append(field.Key+"="+this.PName+"p"+(index));
                }else{
                    sb.Append(field.Key+"="+this.PName+"p"+(index)+",");
                }
            }
            if (entity.WhereExpression==null) {
                throw new Exception("entity.WhereExpression==null");
            }
            else{
                string whereContent=entity.WhereExpression.WhereContent;
                //
                StringBuilder retSB = new StringBuilder ();
                
                for (int i=0; i<whereContent.Length; i++) {
                    Char c=whereContent [i];
                    if ('@' == c) {
                        index++;
                        retSB.Append (PName+"p" + index);
                        
                    } else {
                        retSB.Append (c);
                    }
                }
                //
                sb.Append(" where "+retSB.ToString());
            }
            return sb;
        }
        
        /// <summary>
        /// 获取添加数据所用的sql
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public StringBuilder GetAddSQL(EntityBase entity){
            Dictionary<string,object> all=entity.ChangedMap;
            var attributes=entity.GetType().GetCustomAttributes(true);
            string tableName=string.Empty;
            if(attributes.Length>0)
            {
                TableAttribute table=attributes[0as TableAttribute;
                if (table==null) {
                    table=attributes[1as TableAttribute;
                }
                tableName=table.TableName;
            }
            else
            {
                throw new Exception("实体类的没有table标记");
            }
            StringBuilder sb=new StringBuilder();
            sb.Append("insert into "+tableName+"(");
            int index=0;
            
            foreach (KeyValuePair<string,object> field in all) {
                index++;
                if (index==all.Count) {
                    sb.Append(field.Key+") values (");
                }
                else{
                    sb.Append(field.Key+",");
                }
            }
            
            for (int i = index; i >0; i--) {
                var p=index-i+1;
                string mp;
                if (i==1) {
                    mp=PName+"p"+p+")";
                }else{
                    mp=PName+"p"+p+",";
                }
                sb.Append(mp);
            }
            return sb;
        }
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns>如果系统自动设置主键,则返回该主键</returns>
        public virtual object Add(EntityBase entity){
            return null;
        }
        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual int Update(EntityBase entity){
            return -1;
        }
        /// <summary>
        /// 通过WhereExpression删除实体,注意WhereExpression描述的是同一个表
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public virtual int Remove(WhereExpression expression){
            return -1;
        }
        /// <summary>
        /// 获取数据条数,注意WhereExpression描述的是同一个表
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public virtual long GetCount(WhereExpression expression)
        {
            return -1;
        }
        /// <summary>
        /// 获取数据条数,注意WhereExpression描述的是同一个表
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public virtual long GetInt32Count(WhereExpression expression)
        {
            return -1;
        }
        /// <summary>
        /// 获取当前的count sql语句
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public StringBuilder GetCountSQL(WhereExpression expression)
        {
            string tableName = expression.WhereContent.Split('.')[0];
            string sql = "select count(1) from  " + tableName + " where " + expression.WhereContent;
            StringBuilder retSB = new StringBuilder();
            int index = 1;
            for (int i = 0; i < sql.Length; i++) {
                Char c = sql[i];
                if ('@' == c) {
                    retSB.Append(PName+"p" + index);
                    index++;
                } else {
                    retSB.Append(c);
                }
            }
            return retSB;
        }
        
        /// <summary>
        /// 移除指定表,T例如:UserSet
        /// </summary>
        /// <returns></returns>
        public virtual int Remove<T>()where T:MQLBase{
            return -1;
        }
        /// <summary>
        /// 获取指定实体集
        /// </summary>
        /// <param name="mql"></param>
        /// <returns></returns>
        public virtual List<T> GetEntities<T>(MQLBase mql) where T: EntityBase,new(){
            return null;
        }
        /// <summary>
        /// 获取自定义实体集
        /// </summary>
        /// <param name="mql"></param>
        /// <returns></returns>
        public virtual List<T> GetOwnList<T>(MQLBase mql) where T: new(){
            return null;
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="mql"></param>
        /// <returns></returns>
        public virtual T GetEntity<T>(MQLBase mql) where T: EntityBase,new(){
            return null;
        }
        /// <summary>
        /// 获取结构的第一行第一列数据
        /// </summary>
        /// <param name="mql"></param>
        /// <returns></returns>
        public virtual Object ExecuteScalar(MQLBase mql){
            return -1;
        }
        /// <summary>
        /// 获取结构的第一行第一列数据
        /// </summary>
        /// <param name="mql"></param>
        /// <returns></returns>
        public  MObject ExecuteScalarToMObject(MQLBase mql){
            var obj= ExecuteScalar(mql);
            MObject ret=new MObject();
            ret.Value=obj;
            return ret;
        }
        /// <summary>
        /// 执行存储过程结果反馈到DataSet
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="procName"></param>
        /// <returns></returns>
        public virtual DataSet ExecuteProToDataSet(String procName,params DbParameter[] parameters){
            return null;
        }
        /// <summary>
        /// 执行存储过程,返回受影响的行数
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="procName"></param>
        /// <returns></returns>
        public virtual int ExecuteProWithNonQuery(String procName,params DbParameter[] parameters){
            return -1;
        }
        /// <summary>
        /// 执行存储过程结果反馈到List
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="procName"></param>
        /// <returns></returns>
        public virtual List<T> ExecuteProToOwnList<T>(String procName,params DbParameter[] parameters)where T:new(){
            return null;
        }
        
        /// <summary>
        /// 资源释放
        /// </summary>
        public void Dispose()
        {
            if (this.TransactionEnabled) {
                try {
                    Transaction.Commit();
                } catch (Exception ex) {
                    Transaction.Rollback();
                    throw ex;
                }
                finally{
                    if (Connection!=null&&Connection.State!= ConnectionState.Closed) {
                        Connection.Close();
                    }
                }
            }
            if (Connection!=null&&Connection.State!= ConnectionState.Closed) {
                Connection.Close();
            }
        }
        /// <summary>
        /// 执行sql结果反馈到DataSet,自己注意sql注入问题
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="procName"></param>
        /// <returns></returns>
        public  DataSet ExecuteSqlToDataSet(string sql){
            var cmd=AdoMethod.CreateDbCommand();
            cmd.Connection=this.Connection;
            if (TransactionEnabled) {
                cmd.Transaction=this.Transaction ;
            }
            cmd.CommandText=sql;
            
            var adapter =AdoMethod.CreateDataAdapter();
            adapter.SelectCommand=cmd;
            DataSet dataSet = new DataSet();
            adapter.Fill(dataSet);
            return dataSet;
        }
        public virtual DataSet ExecuteSqlToDataSet(string sql,params object[] values){
            return null;
        }
        /// <summary>
        /// 执行sql,返回受影响的行数,自己注意sql注入问题
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="procName"></param>
        /// <returns></returns>
        public  int ExecuteSqlWithNonQuery(string sql){
            var cmd=AdoMethod.CreateDbCommand();
            cmd.Connection=this.Connection;
            if (TransactionEnabled) {
                cmd.Transaction=this.Transaction ;
            }
            cmd.CommandText=sql;
            return cmd.ExecuteNonQuery();
        }
        /// <summary>
        /// 执行sql结果反馈到List,自己注意sql注入问题
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="procName"></param>
        /// <returns></returns>
        public  List<T> ExecuteSqlToOwnList<T>(string sql)where T:new(){
            var cmd = AdoMethod.CreateDbCommand();
            cmd.Connection=this.Connection;
            cmd.CommandType= CommandType.Text;
            cmd.CommandText=sql;
            //
            DbDataReader reader=cmd.ExecuteReader();
            List<T>  list=new List<T>();
            while (reader.Read()) {
                T data=MoonFastInvoker<T>.GetTFrom(reader);
                list.Add(data);
                
            }reader.Close();
            return list;
        }
        
        public virtual List<T> ExecuteSqlToOwnList<T>(string sql,params object[] values)where T:new(){
            return null;
        }
        public virtual int ExecuteSqlWithNonQuery(string sql,params object[] values){
            return -1;
        }
        public virtual  List<Dictionary<string,MObject>> ExecuteSqlToDictionaryList(string sql,params object[] values){
            return null;
        }
        public  List<Dictionary<string,MObject>> ExecuteSqlToDictionaryList(string sql){
            //
            var cmd = AdoMethod.CreateDbCommand();
            cmd.Connection=this.Connection;
            cmd.CommandType= CommandType.Text;
            cmd.CommandText=sql;
            DbDataReader reader=cmd.ExecuteReader();
            //
            List<Dictionary<string,MObject>> list=new List<Dictionary<string, MObject>>();
            while (reader.Read()) {
                Dictionary<string,MObject> entity=new Dictionary<string, MObject>(StringComparer.OrdinalIgnoreCase);
                
                for (int i = 0; i < reader.VisibleFieldCount; i++) {
                    string fieldName=reader.GetName(i);
                    object value=reader.GetValue(i);
                    MObject v=new MObject();
                    v.Value=value;
                    entity.Add(fieldName,v);
                }
                list.Add(entity);
            }
            reader.Close();
            return list;
        }
        public virtual List<Dictionary<string,MObject>> GetDictionaryList(MQLBase mql){
            return null;
        }
    }
}
posted @ 2013-09-07 16:20  [秦时明月]  阅读(1280)  评论(0编辑  收藏  举报