this is the code I am using to back up my database using pg_dump 9.3 in java. The problem I have is that always the result file is empty, and the exit code is 1, any ideas?
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());
}
thanks everyone for help, finally could find the perfect code.
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());
}
}
For psql, the "long options" need an equal sign: =. So it needs to be e.g. --host=localhost. For that you need to pass those arguments as a single String argument to 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");
You should also capture the error output of the ProcessBuilder using ProcessBuilder.getErrorStream() to see any error message from psql. You probably want to capture the regular output as well (using getInputStream())
Edit
The error message you get:
fe_sendauth: no password supplied
means you have to provide a password.
You can do that by passing a connection URL to 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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With