public static string GetDefaultConnectionName() { var tableFeature = new string[] { "sys_button", "sys_code", "sys_codeType", "sys_log", "sys_loginHistory", "sys_roleMenuColumnMap", "sys_user", "sys_menu" }; IDbContext db = null; Configuration config = WebConfigurationManager.OpenWebConfiguration("~/"); foreach (ConnectionStringSettings item in config.ConnectionStrings.ConnectionStrings) { var provider = Db.Provider(item.ProviderName); if (provider == null) continue; //特征检测 db = new DbContext().ConnectionString(item.ConnectionString, provider); var sql = string.Empty; switch (item.ProviderName) { case "SqlServer": sql = string.Format("select name from dbo.sysobjects where name in ('{0}')", string.Join("','", tableFeature)); break; case "MySql": sql = string.Format("select TABLE_NAME as TableName from information_schema.TABLES where TABLE_SCHEMA= database() and TABLE_NAME in ('{0}')", string.Join("','", tableFeature)); break; } if (string.IsNullOrEmpty(sql)) continue; var result = db.Sql(sql).QueryMany<dynamic>(); if (result.Count == tableFeature.Length) return item.Name; } return string.Empty; }
public static List<Table> GetTables(string dbType,string conString) { var gen = GetGenProvider(dbType); var provider = GetProvider(dbType); using (var db = new DbContext().ConnectionString(conString, provider)) { var Tables = db.Sql(gen.SqlGetTableNames()).QueryMany<Table>(); foreach (var T in Tables) { T.TableKeys = db.Sql(gen.SqlGetTableKeys(T.TableName)).QueryMany<TableKey>().Select<TableKey, string>(x => x.column_name).ToList<string>(); T.TableSchemas = db.Sql(gen.SqlGetTableSchemas(T.TableName)).QueryMany<TableSchema>(); } return Tables; } }
public string Execute() { var provider = Db.Provider(providerName); var dbexist = TestConnectionString(); var db = new DbContext().ConnectionString(GetDefaultConnectionString(), provider); //如果数据库不存在,则创建数据库 if (!dbexist) { try { db.Sql(GetScriptCreateDatabase()).Execute(); } catch (Exception e) { db.Dispose(); return e.Message; } } try { //开启事务 db.UseTransaction(true); db.CommandTimeout(60); //创建表结构 var createScript = GetScriptCreateTable(); if (!string.IsNullOrEmpty(createScript)) db.Sql(GetScriptUseDatabase() + createScript).Execute(); //初始化数据 var dataScript = GetScriptInsertData(); if (!string.IsNullOrEmpty(createScript)) db.Sql(GetScriptUseDatabase() + dataScript).Execute(); db.Commit(); } catch (Exception e) { try { db.Rollback(); db.UseTransaction(false); } catch{ } //处理失败,删除刚刚创建的数据库 if (!dbexist) db.Sql(GetScriptDropDatabase()).Execute(); return e.Message; } finally { db.Dispose(); } return string.Empty; }