[英]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.