Search code examples
javaderbyddlutils

Is there any way to convert derby database table rows to SQL insert statements


I have successfully exported the Derby schema using ddlUtils but how do I export table data in derby to insert SQL statements?


Solution

  • If you're willing to use a third-party tool for this, you could use jOOQ

    public class ExportAsInsert {
        public static void main(String[] args) {
            try (DSLContext ctx = DSL.using(url, user, password)) {
                ctx.meta()
                   .getSchemas()
                   .stream()
    
                   // Filter out those schemas that you want to export
                   .filter(schema -> schema.getName().equals("TEST"))
    
                   // Get the tables for each schema...
                   .flatMap(schema -> schema.getTables().stream())
    
                   // ... and format their content as INSERT statements.
                   .forEach(table -> System.out.println(ctx.fetch(table).formatInsert()));
            }
        }
    }
    

    There's a known issue that the above generates the wrong table name in the insert statement. You can fix this by patching the output:

    System.out.println(
        ctx.fetch(table).formatInsert().replace("UNKNOWN_TABLE", table.getName()));
    

    (Disclaimer: I work for the company behind jOOQ)