You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
publicclassDbUpRunner{privatereadonlystring_connectionString;//数据库连接字符串publicDbUpRunner(stringconnectionString){_connectionString=connectionString;}publicvoidRun(){EnsureDatabase.For.MySqlDatabase(_connectionString);//确保数据库是否存在,如果不存在则创建新数据库stringoutPutDirectory=Path.GetFullPath("../PractiseForJohnny.Core/DbUp");//在程序集中查找dbupvarupgradeEngine=DeployChanges.To.MySqlDatabase(_connectionString).WithScriptsAndCodeEmbeddedInAssembly(typeof(DbUpRunner).Assembly, s =>s.EndsWith(".cs")).WithScriptsFromFileSystem(outPutDirectory)//使用WithScriptsFromFileSystem默认选择以.sql结尾的文件.WithTransaction()//用于在执行脚本时启用事务。它确保在执行脚本期间,如果发生错误,将回滚所有已执行的更改.LogToAutodetectedLog()//用于自动检测并配置日志记录器。它根据可用的日志记录库自动选择适当的日志记录器。.LogToConsole()//将日志输出到控制台.Build();//构建升级引擎。varresult=upgradeEngine.PerformUpgrade();//PerformUpgrade:用于执行数据库升级。它将执行所有未执行的脚本,并将执行结果返回给result变量。if(!result.Successful)throwresult.Error;//判断升级是否成功Console.ForegroundColor=ConsoleColor.Green;Console.WriteLine("Success!");Console.ResetColor();}}
3、创建脚本,有两种脚步,一种是sql脚本,一种是代码脚本:
//sql脚本,创建一个文件后缀名为.sqlcreatetable if not exists foods
(Idint not null primary key auto_increment,namevarchar(50)notnull,colorvarchar(10)notnull)charset=utf8mb4;//代码脚本,创建一个类继承IScript,实现接口后,在ProvideScript的写sqlpublicclassScripts0002_initial_tables:IScript{publicstringProvideScript(Func<IDbCommand>dbCommandFactory){return@"create table if not exists Foods ( Id int not null primary key AUTO_INCREMENT, name varchar(50) not null, color varchar(100) not null ) charset=utf8mb4";}}