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

徘徊边缘 提交于 2019-12-19 03:16:01

问题


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.



来源:https://stackoverflow.com/questions/3810288/how-to-do-a-backup-from-a-postgresql-db-via-jdbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!