如何使用java备份postgres数据库

时间:2016-05-02 23:55:31

标签: java postgresql

这是我用来在java中使用pg_dump 9.3备份我的数据库的代码。 我遇到的问题是结果文件总是空的,退出代码是1,任何想法?

public static void backupDb() throws IOException, InterruptedException {
    Runtime rt = Runtime.getRuntime();
    Process p;
    ProcessBuilder pb;
    rt = Runtime.getRuntime();
    pb = new ProcessBuilder(
            "C:\\Program Files\\PostgreSQL\\9.3\\bin\\pg_dumpall.exe",
            "--host", "localhost",
            "--port", "5432",
            "--username", "postgres",
            "--no-password",
            "--format", "custom",
            "--blobs",
            "--verbose", "--file", "D:\\service_station_backup.backup", "service_station");
    p = pb.start();
    p.waitFor();
    System.out.println(p.exitValue());
}

2 个答案:

答案 0 :(得分:5)

感谢大家的帮助,终于找到了完美的代码。

public static void exportDb2() throws IOException, InterruptedException {
    Runtime rt = Runtime.getRuntime();
    Process p;
    ProcessBuilder pb;
    rt = Runtime.getRuntime();
    pb = new ProcessBuilder(
            "C:\\Program Files\\PostgreSQL\\9.3\\bin\\pg_dump.exe",
            "--host", "localhost",
            "--port", "5432",
            "--username", "postgres",
            "--no-password",
            "--format", "custom",
            "--blobs",
            "--verbose", "--file", "D:\\service_station_backup.backup", "service_station");
    try {
        final Map<String, String> env = pb.environment();
        env.put("PGPASSWORD", "admin");
        p = pb.start();
        final BufferedReader r = new BufferedReader(
                new InputStreamReader(p.getErrorStream()));
        String line = r.readLine();
        while (line != null) {
            System.err.println(line);
            line = r.readLine();
        }
        r.close();
        p.waitFor();
        System.out.println(p.exitValue());

    } catch (IOException | InterruptedException e) {
        System.out.println(e.getMessage());
    }
}

答案 1 :(得分:0)

对于psql,&#34;长选项&#34;需要一个等号:=。所以它需要是例如--host=localhost。为此,您需要将这些参数作为单个String参数传递给ProcessBuilder:

pb = new ProcessBuilder(
        "C:\\Program Files\\PostgreSQL\\9.3\\bin\\pg_dumpall.exe",
        "--host=localhost",
        "--port=5432",
        "--username=postgres",
        "--no-password",
        "--format=custom",
        "--blobs",
        "--verbose", "--file=D:\\service_station_backup.backup", "service_station");

您还应该使用ProcessBuilder.getErrorStream()捕获ProcessBuilder的错误输出,以查看来自psql的任何错误消息。您可能也希望捕获常规输出(使用getInputStream()

修改

您收到的错误消息:

  

fe_sendauth:未提供密码

表示您必须提供密码。

您可以通过将connection URL传递给pg_dump来实现。

pb = new ProcessBuilder(
        "C:\\Program Files\\PostgreSQL\\9.3\\bin\\pg_dumpall.exe",
        "--dbname=postgres://postgres:password@localhost/postgres",
        "--format=custom",
        "--blobs",
        "--verbose", "--file=D:\\service_station_backup.backup", "service_station");