Esempio n. 1
0
        /// <summary>
        /// 创建连接
        /// </summary>
        /// <param name="dataBaseType"></param>
        /// <returns></returns>
        public static DbConnection CreateDbConnection(DataBaseType dataBaseType)
        {
            DbConnection dbConnection     = null;
            var          dllPath          = "";
            var          dllName          = "";
            var          dbConnectionType = "";

            if (dataBaseType == DataBaseType.SqlServer)
            {
                return(new SqlConnection());
            }
            switch (dataBaseType)
            {
            case DataBaseType.MySql:
                dllName          = "MySql.Data.dll";
                dbConnectionType = "MySql.Data.MySqlClient.MySqlConnection";
                break;

            case DataBaseType.SQLite:
                dllName          = "System.Data.SQLite.DLL";
                dbConnectionType = "System.Data.SQLite.SQLiteConnection";
                break;

            case DataBaseType.Oracle:
                dllName          = "Oracle.DataAccess.dll";
                dbConnectionType = "Oracle.DataAccess.Client.OracleConnection";
                break;

            case DataBaseType.Postgresql:
                dllName          = "Npgsql.dll";
                dbConnectionType = "Npgsql.NpgsqlConnection";
                break;
            }
            dllPath = AppDomain.CurrentDomain.BaseDirectory + "bin\\" + dllName;
            Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "bin\\");
            if (!File.Exists(dllPath))
            {
                switch (dataBaseType)
                {
                case DataBaseType.MySql:
                    File.WriteAllBytes(dllPath, Properties.Resources.MySql_Data);
                    break;

                case DataBaseType.Oracle:
                    if (Environment.Is64BitOperatingSystem)
                    {
                        File.WriteAllBytes(dllPath, Properties.Resources.Oracle_DataAccess_64);
                    }
                    else
                    {
                        File.WriteAllBytes(dllPath, Properties.Resources.Oracle_DataAccess_86);
                    }
                    break;

                case DataBaseType.Postgresql:
                    File.WriteAllBytes(dllPath, Properties.Resources.Npgsql);
                    break;

                case DataBaseType.SQLite:
                    File.WriteAllBytes(dllPath, Properties.Resources.System_Data_SQLite);
                    break;

                default:
                    throw new FileNotFoundException(RS.STRING_DB_DLL_NOT_EXISTS(dataBaseType));
                }
            }
            var connectionType = Assembly.LoadFile(dllPath).GetType(dbConnectionType);

            dbConnection = (DbConnection)Activator.CreateInstance(connectionType);
            return(dbConnection);
        }