我将两个数据库与liquibase java API 3.3.2进行了比较,然后生成了changelog.xml文件。现在,我想生成将更新目标数据库的sql脚本。 这是我的代码:
Database database;
Database database2;
try {
database = CommandLineUtils.createDatabaseObject(org.postgresql.Driver.class.getClassLoader(), "jdbc:postgresql://localhost:5432/loan", "postgres", "", "org.postgresql.Driver", null, null, false, false, null, null, null, null, null);
database2=CommandLineUtils.createDatabaseObject(org.postgresql.Driver.class.getClassLoader(), "jdbc:postgresql://localhost:5432/loan2", "postgres", "", "org.postgresql.Driver", null, null, false, false, null, null, null, null, null);
Liquibase liquibase = new Liquibase("", new FileSystemResourceAccessor(), database);
DiffResult result = liquibase.diff(database, database2, new CompareControl());
DiffToChangeLog diffLog = new DiffToChangeLog(result, new DiffOutputControl());
diffLog.print(System.out);
//new DiffToReport(result, System.out).print();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
修改 以下是我的表现,感谢Steve donie:
Database database;
Database database2;
try {
database = CommandLineUtils.createDatabaseObject(org.postgresql.Driver.class.getClassLoader(), "jdbc:postgresql://localhost:5432/loan", "postgres", "", "org.postgresql.Driver", null, null, false, false, null, null, null, null, null);
database2= CommandLineUtils.createDatabaseObject(org.postgresql.Driver.class.getClassLoader(), "jdbc:postgresql://localhost:5432/loan2", "postgres", "", "org.postgresql.Driver", null, null, false, false, null, null, null, null, null);
// generate the changelog that contains the differences
CommandLineUtils.doDiffToChangeLog("changelog.xml", database, database2, new DiffOutputControl(), null, null);
// generate the sql script from the changeLog (without executing it)
File sql = new File("output.sql");
Liquibase liquibase = new Liquibase("changelog.xml", new FileSystemResourceAccessor(), database);
liquibase.update("Update", new FileWriter(sql));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:0)
解决这个问题的一种方法是从命令行运行时查看Liquibase本身的功能。在这种情况下,您通常会使用diffChangeLog命令创建更改日志,然后运行updateSQL以生成更新数据库所需的SQL。查看liquibase.integration.commandline.Main
的Liquibase源代码,我看到what it does is to use the Liquibase.update() method带有指定a non-null output writer的参数(这是SQL将保存到的文件)。