/// <summary>
 /// 上下文初始化器(只赋值,不初始化,有可能被重复创建两次)
 /// </summary>
 /// <param name="connectionString">连接字符串</param>
 /// <param name="dbType">数据库类型</param>
 /// <param name="commandTimeout">命令超时时间</param>
 /// <param name="dataVer">数据库版本</param>
 public ContextConnection(string connectionString, DataBaseType dbType, int commandTimeout, string dataVer)
 {
     this.ConnectionString = connectionString;
     this.DbType = dbType;
     this.CommandTimeout = commandTimeout;
     this.DataVer = dataVer;
 }
Beispiel #2
0
 public DBHelper(ConnectionType conncetionType, DataBaseType DBMSType,string strDBFileNamePath)
 {
     DbConnectionType = conncetionType;
     dbType = DBMSType;
     S_DBFILENAME = strDBFileNamePath;
     oFactory = DbProviderFactories.GetFactory(RetreiveConnectionString());
 }
Beispiel #3
0
        public bool CreateDataBase(DataBaseType nType, string nConnectionString, byte[] nRemotingPassword, out DataBase nDataBase, out string nMessage)
        {
            nMessage = "";
            nDataBase = null;

            try
            {
                if (this.ServerPassword == Crypto.RSADecryptText(nRemotingPassword, this.ServerPrivateKey))
                {
                    nDataBase = DataBaseFactory.CreateDatabase(nType, DataBaseFactory.GetInnerConnectionString(nConnectionString));

                    nDataBase._proxy = this;

                    this._DataBaseList.Add(nDataBase._token, nDataBase);

                    return true;
                }
                else
                {
                    throw new Exception("La contraseña de acceso al servidor remoting no es válida");
                }
            }
            catch (Exception ex)
            {
                nMessage = ex.Message;
            }

            return false;
        }
        private ExtractObjectsArgs GetFunctionExtractObjectsArgs(DataBaseType dbType)
        {
            switch (dbType)
            {
                case DataBaseType.Oracle:
                    return new ExtractObjectsArgs(
                        Settings.Oracle.Function.Default.Regex,
                        _inputText,
                        Settings.Oracle.Function.Default.DropEnding,
                        Settings.Oracle.Function.Default.DropReplace,
                        Settings.Oracle.Function.Default.CreateEnding,
                        Settings.Oracle.Function.Default.CreateSearch,
                        Settings.Oracle.Function.Default.CreateReplace,
                        _functions,
                        delegate(string str) { return str.Equals("\r\nBEGIN\r\nRETURN NULL;\r\n"); });

                case DataBaseType.SQLServer:
                    return new ExtractObjectsArgs(
                        Settings.SQLServer.Function.Default.Regex,
                        _inputText,
                        Settings.SQLServer.Function.Default.DropEnding,
                        Settings.SQLServer.Function.Default.DropReplace,
                        Settings.SQLServer.Function.Default.CreateEnding,
                        Settings.SQLServer.Function.Default.CreateSearch,
                        Settings.SQLServer.Function.Default.CreateReplace,
                        _functions,
                        delegate(string str) { return str.Equals(" begin\r\nreturn NULL\r\n"); });

                default:
                    throw new NotSupportedException(
                        String.Format("{0} is not a valid DataBase Type!",
                        (DataBaseType)dbType));
            }
        }
Beispiel #5
0
        public static ConnectionString GetConnectionString(string connectionString, DataBaseType type)
        {
            var values = connectionString.Split((";").ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            var eConnectionString = new ConnectionString();

            eConnectionString.String = connectionString;
            eConnectionString.Type = type;

            switch (eConnectionString.Type)
            {
                case DataBaseType.SqlServer:
                    eConnectionString.Server = values[0].Split('=')[1];
                    eConnectionString.DataSource = values[1].Split('=')[1];
                    eConnectionString.User = values[2].Split('=')[1];
                    eConnectionString.Password = values[3].Split('=')[1];
                    break;
                case DataBaseType.Oracle:
                    eConnectionString.DataSource = values[0].Split('=')[1];
                    eConnectionString.User = values[1].Split('=')[1];
                    eConnectionString.Password = values[2].Split('=')[1];
                    break;
            }

            return eConnectionString;
        }
Beispiel #6
0
 private void PlotVarDB_Load(object sender, EventArgs e)
 {
     database = new DataBaseType();
     database.ME1 = new List<PlotVarEntry>();
     database.ME2 = new List<PlotVarEntry>();
     database.ME3 = new List<PlotVarEntry>();
 }
        public string DbGetVersion(DataBaseType dbType)
        {
            if (dbType == DataBaseType.Mssql)
            return "@@VERSION";

             return "VERSION()";
        }
        public string GetDatarowsCount(string databaseName, string tableName, DataBaseType dbType)
        {
            if (dbType == DataBaseType.Mssql)
            return "SELECT LTRIM(STR(COUNT(*))) FROM " + databaseName + ".." + tableName + "";

             return "SELECT COUNT(*) FROM " + databaseName + "." + tableName;
        }
        public string GetDatabaseCountQuery(DataBaseType dbType)
        {
            if (dbType == DataBaseType.Mssql)
            return "SELECT LTRIM(STR(COUNT(name))) FROM master..sysdatabases";

             return "SELECT COUNT(schema_name) FROM information_schema.SCHEMATA";
        }
        public string DbGetUser(DataBaseType dbType)
        {
            if (dbType == DataBaseType.Mssql)
            return "SYSTEM_USER";

             return "CURRENT_USER()";
        }
        public string DbGetDatabase(DataBaseType dbType)
        {
            if (dbType == DataBaseType.Mssql)
            return "DB_NAME()";

             return "DATABASE()";
        }
Beispiel #12
0
        public DBAccess(DataBaseType dbType,string connectionString)
        {
            this._dbType = dbType;
            this._connectionString = connectionString;

            this.dbAccess= new DataBaseAccess(this._dbType, this._connectionString);
        }
 /// <summary>
 ///     默认第一个数据库配置
 /// </summary>
 /// <param name="connectionString">数据库连接字符串</param>
 /// <param name="dbType">数据库类型</param>
 /// <param name="dataVer">数据库版本</param>
 /// <param name="commandTimeout">SQL执行超时时间</param>
 public ContextAttribute(string connectionString, DataBaseType dbType = DataBaseType.SqlServer, string dataVer = "2008", int commandTimeout = 30)
 {
     ConnStr = connectionString;
     DataType = dbType;
     DataVer = dataVer;
     CommandTimeout = commandTimeout;
 }
        public string GetDatabaseNameQuery(DataBaseType dbType, int dbIndex)
        {
            if (dbType == DataBaseType.Mssql)
            return "SELECT TOP 1 name FROM master..sysdatabases WHERE name NOT IN (SELECT TOP " + dbIndex +
                   " name FROM master..sysdatabases ORDER BY name)";

             return "SELECT schema_name FROM information_schema.SCHEMATA LIMIT " + dbIndex + ", 1";
        }
Beispiel #15
0
        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <param name="connnection">数据库连接字符串</param>
        /// <param name="commandTimeout">数据库执行时间,单位秒</param>
        /// <param name="tranLevel">开启事务等级</param>
        public DbExecutor(DataBaseType dbType, string connnection, int commandTimeout, IsolationLevel tranLevel = IsolationLevel.Unspecified)
        {
            ConnectionString = connnection.Replace("|RootDirectory|", AppDomain.CurrentDomain.BaseDirectory, RegexOptions.IgnoreCase);
            CommandTimeout = commandTimeout;
            DataType = dbType;

            OpenTran(tranLevel);
        }
 /// <summary>
 /// 返回数据库操作
 /// </summary>
 /// <param name="databaseName">数据库名称</param>
 /// <param name="dbType">数据库类型</param>
 /// <returns>返回数据库</returns>
 internal static Database GetDataBase(string databaseName,DataBaseType dbType)
 {
     if(dbType == DataBaseType.Write)
      {
          return  DatabaseFactory.GetWriteDatabase(databaseName);
      }
      return  DatabaseFactory.GetReadDatabase(databaseName);
 }
Beispiel #17
0
        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="commandTimeout">数据库执行时间,单位秒</param>
        /// <param name="tranLevel">开启事务等级</param>
        public DbExecutor(string connectionString, DataBaseType dbType = DataBaseType.SqlServer, int commandTimeout = 30, IsolationLevel tranLevel = IsolationLevel.Unspecified)
        {
            _connectionString = connectionString;
            _commandTimeout = commandTimeout;
            DataType = dbType;

            OpenTran(tranLevel);
        }
 public Request()
 {
     NaturalRequestNr = 0;
      URL = string.Empty;
      POST = string.Empty;
      HTML = string.Empty;
      DataBaseType = DataBaseType.Unknown;
      Function = string.Empty;
 }
 public InternalData()
 {
     Prepared = false;
      ParameterInjectable = false;
      InjectableCondition = string.Empty;
      InjectableBegin = string.Empty;
      InjectableEnd = string.Empty;
      DataBaseType = DataBaseType.Unknown;
      UseConditions = true;
 }
Beispiel #20
0
 /// <summary>
 /// 生成分页语句
 /// </summary>
 /// <param name="dbType">数据库类型</param>
 /// <param name="sqlAllFields">查询字段,支持多表查询</param>
 /// <param name="sqlTablesAndWhere">查询的表如果包含查询条件一并带上</param>
 /// <param name="indexField">用以分页的不能重复的索引字段名</param>
 /// <param name="orderFields">排序字段以及排序方式</param>
 /// <param name="pageIndex">当前的页码</param>
 /// <param name="pageSize">每页记录数</param>
 /// <returns></returns>
 public static string GetPageSql(DataBaseType dbType, string sqlAllFields, string sqlTablesAndWhere, string indexField, string orderFields, int pageIndex, int pageSize)
 {
     switch (dbType)
     {
         case DataBaseType.SqlServer:
             return GetPageSqlServer(sqlAllFields, sqlTablesAndWhere, indexField, orderFields, pageIndex, pageSize);
         default:
             return "分页算法暂未实现。";
     }
 }
Beispiel #21
0
        /// <summary>
        ///     压缩数据库
        /// </summary>
        /// <param name="dataType">数据库类型</param>
        /// <param name="connetionString">连接字符串</param>
        public static void Compression(string connetionString, DataBaseType dataType = DataBaseType.SqlServer)
        {
            var db = new DbExecutor(connetionString, dataType, 30);
            switch (dataType)
            {
                case DataBaseType.SQLite: db.ExecuteNonQuery(CommandType.Text, "VACUUM", null); break;

                default: throw new NotImplementedException("该数据库不支持该方法!");
            }
        }
        public string GetDatarowValue(string databaseName, string tableName, string fieldName, int row,
                                    string orderByColumn, DataBaseType dbType)
        {
            if (dbType == DataBaseType.Mssql)
            return "SELECT TOP 1 CAST(" + fieldName + " as varchar) FROM (SELECT TOP " + Convert.ToString(1 + row) +
                   " * FROM " + databaseName + ".." + tableName + " ORDER BY " + orderByColumn +
                   ") AS newTable ORDER BY " + orderByColumn + " DESC";

             return "SELECT " + fieldName + " FROM " + databaseName + "." + tableName + " ORDER BY " + orderByColumn +
                " LIMIT " + row + ", 1";
        }
Beispiel #23
0
        /// <summary>
        /// 初始化数据库
        /// </summary>
        public static void Initialize(DataBaseType type,string _connectionString)
        {
            DbHelper.connectionString = _connectionString;
            DbType = type;

            //初始化DALBase对象属性
            DALBase.Initialize(type, _connectionString);
            
            //清除数据
            //WatchServiceRegister.Register();
        }
Beispiel #24
0
 /// <summary>
 /// 获取数据库连接对象
 /// </summary>
 /// <param name="dbType">数据库类型</param>
 /// <param name="connectionString">连接字符串</param>
 public static DbConnection GetDbConnection(DataBaseType dbType, string connectionString)
 {
     DbConnection conn;
     switch (dbType)
     {
         case DataBaseType.SqlServer: conn = new SqlConnection(connectionString); ; break;
         default: conn = CreateDbProviderFactory(dbType).CreateConnection(); break;
     }
     conn.ConnectionString = connectionString;
     return conn;
 }
 ////参数前缀
 //private string _prefix = string.Empty;
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="name">参数名称</param>
 /// <param name="dbType">参数类型</param>
 /// <param name="sqlDbType">SqlServer参数类型</param>
 /// <param name="oracleType">Oracle参数类型</param>
 /// <param name="_direction">参数类型(输入、输出、输入输出)</param>
 /// <param name="value">参数值</param>
 /// <param name="size">参数长度</param>
 /// <param name="dataBaseType">数据库类型</param>
 public YicelParameter(string name, DbType dbType, SqlDbType sqlDbType,
     ParameterDirection direction, object value, int size, DataBaseType dataBaseType)
 {
     _name = name;
     _dbType = dbType;
     _sqlDbType = sqlDbType;
     _direction = direction;
     _value = value;
     _size = size;
     _dataBaseType = dataBaseType;
 }
 private DbConnectionString(DataBaseType DbType, String DataSource, String UserName, String Password, String DataBase, Int32 Port = 0, Boolean IsPooling = true, String EncodingName = "utf8")
 {
     this._DataSource = DataSource;
     this._UserID = UserName;
     this._Password = Password;
     this._DbType = DbType;
     this._Port = Port;
     this._IsPooling = IsPooling;
     this._EncodingName = EncodingName;
     this._DataBase = DataBase;
 }
        public string GetDatarowsLength(string databaseName, string tableName, string fieldName, int row,
                                      DataBaseType dbType)
        {
            if (dbType == DataBaseType.Mssql)
            return "SELECT TOP 1 CAST(LEN(CAST(" + fieldName + " as varchar)) as varchar) FROM (SELECT TOP " +
                   Convert.ToString(1 + row) + " * FROM " + databaseName + ".." + tableName + " ORDER BY " + fieldName +
                   ") AS newTable ORDER BY " + fieldName + " DESC";

             return "SELECT LENGTH(" + fieldName + ") FROM " + databaseName + "." + tableName + " ORDER BY " +
                tableName + " LIMIT " + row + ", 1";
        }
 /// <summary>
 /// 获取指定的数据库连接
 /// </summary>
 /// <param name="dataBaseType">数据库类型</param>
 /// <param name="connectionString">数据库连接串</param>
 /// <returns>数据库访问类</returns>
 public static IDbHelper GetHelper(DataBaseType dataBaseType = DataBaseType.SqlServer, string connectionString = null)
 {
     // 这里是每次都获取新的数据库连接,否则会有并发访问的问题存在
     string dbHelperClass = BaseBusinessLogic.GetDbHelperClass(dataBaseType);
     IDbHelper dHelper = (IDbHelper)Assembly.Load(BaseSystemInfo.DbHelperAssmely).CreateInstance(dbHelperClass, true);
     if (!string.IsNullOrEmpty(connectionString))
     {
         dHelper.ConnectionString = connectionString;
     }
     return dHelper;
 }
        /// <summary>
        /// Retorna um Objeto genérico de Conexão
        /// </summary>
        /// <param name="type">Tipo de Banco de Dados a ser usado</param>
        /// <param name="connectionString">String de Conexão para acesso ao Banco de Dados</param>
        public static DbConnection CreateConnection(DataBaseType type, string connectionString)
        {
            switch(type)
            {
                case DataBaseType.SqlServer:
                return new SqlConnection(connectionString);

                case DataBaseType.MsAccess:
                return new OleDbConnection(connectionString);
            }
            return null;
        }
Beispiel #30
0
 /// <summary>
 /// 返回数据库类型名称
 /// </summary>
 /// <param name="dbType">数据库类型</param>
 public static DbProviderFactory CreateDbProviderFactory(DataBaseType dbType)
 {
     switch (dbType)
     {
         case DataBaseType.MySql: return DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
         case DataBaseType.OleDb: return DbProviderFactories.GetFactory("System.Data.OleDb");
         case DataBaseType.Oracle: return DbProviderFactories.GetFactory("System.Data.OracleClient");
         case DataBaseType.SQLite: return DbProviderFactories.GetFactory("System.Data.SQLite");
         case DataBaseType.SqlServer: return DbProviderFactories.GetFactory("System.Data.SqlClient");
     }
     return DbProviderFactories.GetFactory("System.Data.SqlClient");
 }
Beispiel #31
0
 /// <summary>
 /// Executes a select query using the specified predicate, returning an IEnumerable data typed as per T.
 /// Data returned is dependent upon the specified page and resultsPerPage.
 /// </summary>
 public static IEnumerable <TReturn> GetPage <T, TReturn>(this IDbConnection connection, object predicate, IList <ISort> sort, int page, int resultsPerPage, IDbTransaction transaction = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType)
     where T : class
     where TReturn : class
 {
     return(Instance(dbType).GetPage <T, TReturn>(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout));
 }
Beispiel #32
0
 public static IEnumerable <T> GetPage <T>(this IDbConnection connection, int page, int resultsPerPage, out long allRowsCount, string sql, dynamic param = null, string allRowsCountSql = null, IDbTransaction transaction = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     return(Instance(dbType).GetPage <T>(connection, page, resultsPerPage, out allRowsCount, sql, param, allRowsCountSql, transaction, commandTimeout));
 }
Beispiel #33
0
 public static IEnumerable <T> GetPage <T>(string connKey, int page, int resultsPerPage, out long allRowsCount, string sql, dynamic param = null, string allRowsCountSql = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     using (IDbConnection conn = DBUtils.CreateDBConnection(dbType, connKey))
     {
         return(GetPage <T>(conn, page, resultsPerPage, out allRowsCount, sql, param, allRowsCountSql, null, commandTimeout, dbType));
     }
 }
Beispiel #34
0
        /// <summary>
        /// 为指定的表架构生成SQL(Create Table)语句
        /// </summary>
        public static bool CreateTable(string tableName, MDataColumn columns, string conn)
        {
            if (string.IsNullOrEmpty(tableName) || tableName.Contains("(") && tableName.Contains(")"))
            {
                return(false);
            }
            bool         result   = false;
            DataBaseType dalType  = GetDataBaseType(conn);
            string       dataBase = string.Empty;

            switch (dalType)
            {
            case DataBaseType.Txt:
            case DataBaseType.Xml:
                // string a, b, c;
                conn = AppConfig.GetConn(conn);       // CYQ.Data.DAL.DalCreate.GetConnString(conn, out a, out b, out c);
                if (conn.ToLower().Contains(";ts=0")) //不写入表架构。
                {
                    //增加缓存

                    result = true;
                }
                else
                {
                    tableName = Path.GetFileNameWithoutExtension(tableName);
                    string fileName = NoSqlConnection.GetFilePath(conn) + tableName + ".ts";
                    result   = columns.WriteSchema(fileName);
                    dataBase = GetDBInfo(conn).DataBaseName;
                }
                break;

            default:
                #region MyRegion


                using (MProc proc = new MProc(null, conn))
                {
                    dataBase = proc.DataBaseName;
                    try
                    {
                        proc.dalHelper.IsRecordDebugInfo = false;
                        proc.SetAopState(Aop.AopOp.CloseAll);
                        proc.ResetProc(GetCreateTableSql(tableName, columns, proc.DataBaseType, proc.DataBaseVersion));    //.Replace("\n", string.Empty)
                        result = proc.ExeNonQuery() > -2;
                        if (result)
                        {
                            //获取扩展说明
                            string descriptionSql = GetCreateTableDescriptionSql(tableName, columns, proc.DataBaseType).Replace("\r\n", " ").Trim(' ', ';');
                            if (!string.IsNullOrEmpty(descriptionSql))
                            {
                                if (proc.DataBaseType == DataBaseType.Oracle)
                                {
                                    foreach (string sql in descriptionSql.Split(';'))
                                    {
                                        proc.ResetProc(sql);
                                        if (proc.ExeNonQuery() == -2)
                                        {
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    proc.ResetProc(descriptionSql);
                                    proc.ExeNonQuery();
                                }
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        Log.Write(err, LogType.DataBase);
                    }
                    finally
                    {
                        if (proc.RecordsAffected == -2)
                        {
                            _ErrorMsg.AppendLine("CreateTable:" + proc.DebugInfo);
                        }
                    }
                }
                #endregion
                break;
            }
            if (result)
            {
                CrossDB.Add(tableName, "U", conn);//修改缓存。
            }
            return(result);
        }
 public ObjectToSqlHelper(DataBaseType type)
 {
     DatabaseType = type;
 }
Beispiel #36
0
 /// <summary>
 /// 获取指定的表架构生成的SQL(Create Table)的说明语句
 /// </summary>
 public static string GetCreateTableDescriptionSql(string tableName, MDataColumn columns, DataBaseType dalType)
 {
     return(SqlCreateForSchema.CreateTableDescriptionSql(tableName, columns, dalType));
 }
Beispiel #37
0
 public static LambdaUpdateHelper <T> LambdaUpdate <T>(this IDbConnection connection, IDbTransaction transaction = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     return(Instance(dbType).LambdaUpdate <T>(connection, transaction, commandTimeout));
 }
Beispiel #38
0
 public static int Count <T>(string connKey, object predicate, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     using (IDbConnection conn = DBUtils.CreateDBConnection(dbType, connKey))
     {
         return(Count <T>(conn, predicate, null, commandTimeout, dbType));
     }
 }
Beispiel #39
0
 public static IMultipleResultReader GetMultiple(string connKey, GetMultiplePredicate predicate, int?commandTimeout = null, DataBaseType dbType = DefaultDBType)
 {
     using (IDbConnection conn = DBUtils.CreateDBConnection(dbType, connKey))
     {
         return(GetMultiple(conn, predicate, null, commandTimeout, dbType));
     }
 }
Beispiel #40
0
        /// <summary>
        /// Executes a query for the specified id, returning the data typed as per T
        /// </summary>
        public static TReturn Get <T, TReturn>(this IDbConnection connection, dynamic id, IDbTransaction transaction = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType)
            where T : class
            where TReturn : class
        {
            var result = Instance(dbType).Get <T, TReturn>(connection, id, transaction, commandTimeout);

            return((TReturn)result);
        }
Beispiel #41
0
 /// <summary>
 /// Executes a query for the specified id, returning the data typed as per T
 /// </summary>
 public static TReturn Get <T, TReturn>(string connKey, dynamic id, int?commandTimeout = null, DataBaseType dbType = DefaultDBType)
     where T : class
     where TReturn : class
 {
     using (IDbConnection conn = DBUtils.CreateDBConnection(dbType, connKey))
     {
         return(Get <T, TReturn>(conn, id, null, commandTimeout, dbType));
     }
 }
Beispiel #42
0
 public PedidoRepository(IConnectionDB connection, IOptions <KeysConfig> chaveConfiguracao) : base(connection)
 {
     _iChaveConfiguracao = chaveConfiguracao;
     DataBaseType        = (DataBaseType)Enum.Parse(typeof(DataBaseType), _iChaveConfiguracao.Value.TypeDB, true);
 }
Beispiel #43
0
 /// <summary>
 /// 将各数据库默认值格式化成标准值,将标准值还原成各数据库默认值
 /// </summary>
 /// <param name="flag">[0:转成标准值],[1:转成各数据库值]</param>
 /// <returns></returns>
 public static string FormatDefaultValue(DataBaseType dalType, object value, int flag, SqlDbType sqlDbType)
 {
     return(SqlFormat.FormatDefaultValue(dalType, value, flag, sqlDbType));
 }
Beispiel #44
0
        //private static List<string> flag = new List<string>(2);
        //internal static void CreateSelectBaseProc(DalType dal, string conn)
        //{
        //    try
        //    {
        //        switch (dal)
        //        {
        //            //case DalType.Oracle:
        //            //    if (!flag.Contains("oracle"))
        //            //    {
        //            //        flag.Add("oracle");
        //            //        using (DbBase db = DalCreate.CreateDal(conn))
        //            //        {
        //            //            db.AllowRecordSql = false;
        //            //            object o = db.ExeScalar(string.Format(ExistOracle.Replace("TABLE", "PROCEDURE"), "MyPackage.SelectBase"), false);
        //            //            if (o != null && Convert.ToInt32(o) < 1)
        //            //            {
        //            //                db.ExeNonQuery(SqlPager.GetPackageHeadForOracle(), false);
        //            //                db.ExeNonQuery(SqlPager.GetPackageBodyForOracle(), false);
        //            //            }
        //            //        }
        //            //    }
        //            //    break;
        //            case DalType.MsSql:
        //                if (!flag.Contains("sql"))
        //                {
        //                    flag.Add("sql");//考虑到一个应用不太可能同时使用mssql的不同版本,只使用一个标识。
        //                    using (DbBase db = DalCreate.CreateDal(conn))
        //                    {
        //                        db.IsRecordDebugInfo = false;
        //                        object o = null;
        //                        if (!db.Version.StartsWith("08"))
        //                        {
        //                            //    o = db.ExeScalar(string.Format(Exist2000.Replace("U", "P"), "SelectBase"), false);
        //                            //    if (o != null && Convert.ToInt32(o) < 1)
        //                            //    {
        //                            //        db.ExeNonQuery(SqlPager.GetSelectBaseForSql2000(), false);
        //                            //    }
        //                            //}
        //                            //else
        //                            //{
        //                            o = db.ExeScalar(string.Format(TableSchema.Exist2005, "SelectBase", "P"), false);
        //                            if (o != null && Convert.ToInt32(o) < 1)
        //                            {
        //                                db.ExeNonQuery(SqlCreateForPager.GetSelectBaseForSql2005(), false);
        //                            }
        //                        }
        //                    }
        //                }
        //                break;
        //        }
        //    }
        //    catch (Exception err)
        //    {
        //        Log.Write(err, LogType.DataBase);
        //    }
        //}

        /// <summary>
        /// 为字段或表名添加关键字标签:如[],''等符号
        /// </summary>
        /// <param name="name">表名或字段名</param>
        /// <param name="dalType">数据类型</param>
        /// <returns></returns>
        public static string Keyword(string name, DataBaseType dalType)
        {
            return(SqlFormat.Keyword(name, dalType));
        }
Beispiel #45
0
 public static IEnumerable <TReturn> GetPage <T, TReturn>(string connKey, object predicate, IList <ISort> sort, int page, int resultsPerPage, int?commandTimeout = null, DataBaseType dbType = DefaultDBType)
     where T : class
     where TReturn : class
 {
     using (IDbConnection conn = DBUtils.CreateDBConnection(dbType, connKey))
     {
         return(GetPage <TReturn>(conn, predicate, sort, page, resultsPerPage, null, commandTimeout, dbType));
     }
 }
Beispiel #46
0
 /// <summary>
 /// Clears the ClassMappers for each type.
 /// </summary>
 public static void ClearCache(DataBaseType dbType = DefaultDBType)
 {
     Instance(dbType).SqlGenerator.Configuration.ClearCache();
 }
Beispiel #47
0
 /// <summary>
 /// Executes a query using the specified predicate, returning an integer that represents the number of rows that match the query.
 /// </summary>
 public static int Count <T>(this IDbConnection connection, object predicate, IDbTransaction transaction = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     return(Instance(dbType).Count <T>(connection, predicate, transaction, commandTimeout));
 }
Beispiel #48
0
 private static string CleanUpMemberExpression(MemberExpression memberEx, DataBaseType type)
 {
     return("");
 }
Beispiel #49
0
 /// <summary>
 /// Executes a select query for multiple objects, returning IMultipleResultReader for each predicate.
 /// </summary>
 public static IMultipleResultReader GetMultiple(this IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType)
 {
     return(Instance(dbType).GetMultiple(connection, predicate, transaction, commandTimeout));
 }
Beispiel #50
0
 public static void Insert <T>(string connKey, IEnumerable <T> entities, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     using (IDbConnection conn = DBUtils.CreateDBConnection(dbType, connKey))
     {
         Insert <T>(conn, entities, null, commandTimeout, dbType);
     }
 }
Beispiel #51
0
 /// <summary>
 /// Gets the appropriate mapper for the specified type T.
 /// If the mapper for the type is not yet created, a new mapper is generated from the mapper type specifed by DefaultMapper.
 /// </summary>
 public static IClassMapper GetMap <T>(DataBaseType dbType = DefaultDBType) where T : class
 {
     return(Instance(dbType).SqlGenerator.Configuration.GetMap <T>());
 }
Beispiel #52
0
 /// <summary>
 /// Executes a delete query for the specified entity.
 /// </summary>
 public static int Delete <T>(this IDbConnection connection, T entity, IDbTransaction transaction = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     return(Instance(dbType).Delete <T>(connection, entity, transaction, commandTimeout));
 }
Beispiel #53
0
 /// <summary>
 /// Generates a COMB Guid which solves the fragmented index issue.
 /// See: http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy
 /// </summary>
 public static Guid GetNextGuid(DataBaseType dbType = DefaultDBType)
 {
     return(Instance(dbType).SqlGenerator.Configuration.GetNextGuid());
 }
Beispiel #54
0
 public static int Delete <T>(string connKey, T entity, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     using (IDbConnection conn = DBUtils.CreateDBConnection(dbType, connKey))
     {
         return(Delete <T>(conn, entity, null, commandTimeout, dbType));
     }
 }
Beispiel #55
0
 /// <summary>
 /// Executes a select query using the specified predicate, returning an IEnumerable data typed as per T.
 /// </summary>
 public static IEnumerable <T> GetList <T>(this IDbConnection connection, object predicate = null, IList <ISort> sort = null, IDbTransaction transaction = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     return(Instance(dbType).GetList <T, T>(connection, predicate, sort, transaction, commandTimeout));
 }
Beispiel #56
0
 public static IEnumerable <T> GetList <T>(string connKey, object predicate = null, IList <ISort> sort = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     using (IDbConnection conn = DBUtils.CreateDBConnection(dbType, connKey))
     {
         return(GetList <T>(conn, predicate, sort, null, commandTimeout, dbType));
     }
 }
Beispiel #57
0
 /// <summary>
 /// Executes an insert query for the specified entity.
 /// </summary>
 public static void Insert <T>(this IDbConnection connection, IEnumerable <T> entities, IDbTransaction transaction = null, int?commandTimeout = null, DataBaseType dbType = DefaultDBType) where T : class
 {
     Instance(dbType).Insert <T>(connection, entities, transaction, commandTimeout);
 }
Beispiel #58
0
        public string LinqToSqlWhereClause <T>(Expression <Func <T, bool> > expression, DataBaseType type)
            where T : class
        {
            var whereClause = " WHERE ";

            if (!expression.Parameters.IsNullOrEmpty())
            {
                var expressionObject = expression.Parameters.First();
                var parameterName    = expression.Parameters.First().Name;

                if (expression.Body is Expression currentExpression)
                {
                    // Works for Execute(x => x.UserAuthentication(something))
                    // where something must be a constant value, a variable,
                    // a field, a property
                    var param = expression.Parameters[0]; //myparameter to cast



                    //var si = new IEnumerable<ParameterExpression>() { };
                    ////////////var run = Expression.Lambda(currentExpression, expression.Parameters).Compile();
                    ////////////var tar = run.Target;
                    ////////////var mi = run.Method;
                    ////////////var r = run.DynamicInvoke();

                    ////////////var body = Expression.TypeAs(expression.Body, typeof(T));

                    ////////////  // If you have a type for the parameter, replace it here:
                    ////////////  // object -> yourtype
                    ////////////  var obj = Expression.Lambda<Func<T>>(expression.Body,param).Compile()();
                    ////////////var source = Expression.Parameter(typeof(T),"source");

                    // (T)expressionObject.Value
                    // var obj = Expression.Lambda<Func<T>>(expressionObject).Compile()();

                    var isFirstTime = true;
                    var holdOff     = "";
                    while (currentExpression != null)
                    {
                        var memberExpression     = currentExpression as MemberExpression;
                        var binaryExpression     = currentExpression as BinaryExpression;
                        var constantExression    = currentExpression as ConstantExpression;
                        var unaryExpression      = currentExpression as UnaryExpression;
                        var methodCallExpression = currentExpression as MethodCallExpression;
                        var isLast = binaryExpression?.Left == null;
                        if (isLast)
                        {
                            _sqlBuilder.Append(holdOff);
                        }
                        //  GetSQLFromMember(memberExpression);
                        if (binaryExpression != null)
                        {
                            isFirstTime = true;
                            var left  = binaryExpression.Left;
                            var right = binaryExpression.Right;
                            var t     = right as BinaryExpression;


                            if (binaryExpression.Left is MemberExpression m1)
                            {
                                GetSQLFromMember(m1, null, binaryExpression);
                            }



                            while (t != null)
                            {
                                var sqlOperator = GetRegisteredOperatorString(binaryExpression.NodeType);
                                if (isFirstTime)
                                {
                                    holdOff     = $" {sqlOperator} ";
                                    isFirstTime = false;
                                }
                                else
                                {
                                }
                                var b1 = t.Left as MemberExpression;
                                var b2 = t.Right as MemberExpression;

                                GetSQLFromMember(b1, b2, t);

                                t = t.Right as BinaryExpression;
                            }
                            memberExpression = right as MemberExpression;
                            var binaryExpression23 = right as BinaryExpression;
                            constantExression = right as ConstantExpression;
                            unaryExpression   = right as UnaryExpression;
                            currentExpression = binaryExpression.Left;
                        }
                        else
                        {
                            currentExpression = null;
                            if (isFirstTime && memberExpression != null)
                            {
                                var middle       = GetRegisteredOperatorString(memberExpression.NodeType);
                                var propertyinfo = memberExpression?.Member as PropertyInfo;
                                var fieldinfo    = memberExpression?.Member as FieldInfo;

                                if (propertyinfo != null)
                                {
                                    _sqlBuilder.Append($" ( {propertyinfo.Name} {middle} {0}) ");
                                }
                            }
                        }


                        currentExpression = Visit(currentExpression);
                        //if (memberEX != null)
                        //{
                        //if (i == 0) // The Last MemberExpression Is Not Wanted After We Find A Least One Binary Expression & When MemberExpression Only Comes In 1'ss
                        //whereClause += CleanUpMemberExpression(memberEX, type) + andSO;
                        //currentExpression = null;
                        //}
                        //if (binaryEX != null)
                        //{
                        //whereClause += CleanUpRightNodyByType(parameterName, binaryEX, type) + andSO;
                        //currentExpression = binaryEX.Left;
                        //}
                        //if (memberEX == null && binaryEX == null)
                        //{
                        //currentExpression = null;
                        //TheMoFaDeDI.Logger.Log("JOSEPH A NEW EXPRESSION IS FOUND IN LINQ 2 SQL");
                        //}
                        //i++;
                    }
                    whereClause = whereClause.ReplaceLastOccurrance(" AND ", string.Empty, StringComparison.Ordinal);
                }
            }

            return(whereClause);
        }
Beispiel #59
0
 /// <summary>
 /// 获取指定的表架构生成的SQL(Create Table)的说明语句
 /// </summary>
 public static string GetCreateTableSql(string tableName, MDataColumn columns, DataBaseType dalType, string version)
 {
     return(SqlCreateForSchema.CreateTableSql(tableName, columns, dalType, version));
 }
Beispiel #60
0
 /// <summary>
 /// 获取指定数据库的数据类型
 /// </summary>
 /// <param name="ms">单元格结构</param>
 /// <param name="dalType">数据库类型</param>
 /// <param name="version">数据库版本号</param>
 /// <returns></returns>
 public static string GetDataType(MCellStruct ms, DataBaseType dalType, string version)
 {
     return(DataType.GetDataType(ms, dalType, version));
 }