How to do a backup from a Postgresql-DB via JDBC?

2020-03-02 20:17发布

问题:

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();
     }

回答1:

Why don't you use pg_dump?



回答2:

The Postgresql JDBC library now supports the bulk COPY operations. See http://jdbc.postgresql.org/documentation/publicapi/index.html?org/postgresql/copy/CopyManager.html

To back up a database, you'll want to CopyOut from the db to a stream, then reverse the process to restore using CopyIn.



回答3:

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.