Basic code to use Flywaydb programmatically

By xngo on February 21, 2019

Flyway is a database migration tool that allow you to manage the state of your database. It is the version control system for database. Even though the migration mechanic is handled by Flyway, you still have to provide the migration scripts either using SQL or Java.

The code example below shows you how to run Flyway using Java. It will execute all your SQL scripts with filename pattern V?__someText.sql. For the code to work, you need:

  • To include flyway-core-3.0.jar and sqlite-jdbc-3.7.2.jar in your classpath.
  • To put all your SQL migration scripts in the folder that you defined from your code and the SQL script filename must follow the pattern V?__someText.sql. ? is the database version number.
package net.xngo.tutorial.java.flywaydb;
 
import org.flywaydb.core.Flyway;
 
/**
 * How to use Flywaydb programmatically.
 * Libraries needed: flyway-core-3.0.jar, sqlite-jdbc-3.7.2.jar
 * 
 */
public class FlywaydbBasic
{
  public static void main(String[] args)
  {
    Flyway flyway = new Flyway();
 
    // Set your datasource.
    flyway.setDataSource("jdbc:sqlite:/C:/temp/test/latest/test/FilesHub.db", null, null);
 
    // Set the location of all your SQL files: V?__*.sql
    flyway.setLocations("filesystem:C:/temp/test/latest/test/sql/");
 
    flyway.setInitDescription("First version database");
 
    // Force the creation of 'schema_version' table on existing database.
    flyway.setInitOnMigrate(true);
 
    // Execute all SQL files from C:\temp\test\latest\sql\ directory
    //                                      with the following pattern: V?__*.sql
    flyway.migrate();
  }
}

Github

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.