views:

47

answers:

2

In our application, we've implemented an automatic DB migration triggered from within our code. Now we want to backup the existing DB before doing any migration.

Can anyone explain how to do a full backup of a Postgresql-DB via JDBC from within Java code?

Update: it doesn't work via JDBC.

Here some working code to the response of Frank Heikens:

    final List<String> baseCmds = new ArrayList<String>();
    baseCmds.add("/usr/bin/pg_dump");
    baseCmds.add("-h");
    baseCmds.add("hostname");
    baseCmds.add("-p");
    baseCmds.add("5432");
    baseCmds.add("-U");
    baseCmds.add("username");
    baseCmds.add("-b");
    baseCmds.add("-v");
    baseCmds.add("-f");
    baseCmds.add("/path/to/backup.sql");
    baseCmds.add("dbName");
    final ProcessBuilder pb = new ProcessBuilder(baseCmds);

    // Set the password
    final Map<String, String> env = pb.environment();
    env.put("PGPASSWORD", "password");

    try {
        final Process process = pb.start();

        final BufferedReader r = new BufferedReader(
                  new InputStreamReader(process.getErrorStream()));
        String line = r.readLine();
        while (line != null) {
            System.err.println(line);
            line = r.readLine();
        }
        r.close();

        final int dcertExitCode = process.waitFor();

     } catch (IOException e) {
        e.printStackTrace();
     } catch (InterruptedException ie) {
        ie.printStackTrace();
     }
A: 

I use DbUnit for backup of a database from within my java application:

DbUnit has the ability to export and import your database data to and from XML datasets. Since version 2.0, DbUnit can also work with very large datasets when used in streaming mode.

tangens
DbUnit doesn't dump SQL. But I didn't tell that in the original question.
boutta
+3  A: 

Why don't you use pg_dump?

Frank Heikens
Because when I use ProcessBuilder to start pg_dump, pg_dump can't access file to write the dump into :(
boutta
Then stream the output of pg_dump to another location. pg_dump is the only secure method to make a backup, all others (except PITR) will fail. And they fail at the worst posible moment.
Frank Heikens
That didn't work either. It ran into a blocking read. I solved the problem, specifying the Filename without any " or '.
boutta