簡體   English   中英

如何使用Java備份Postgres數據庫

[英]How to backup a postgres database using java

這是我用於在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());
}

感謝大家的幫助,終於找到了完美的代碼。

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

對於psql ,“長選項”需要等號: = 因此它必須是--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:未提供密碼

表示您必須提供密碼。

您可以通過將連接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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM