How to backup from Postgresql-DB via JDBC?

In our application, we implemented automatic database migration called from our code. Now we want to make a backup copy of the existing database before performing any migration.

Can someone explain how to make a full backup of Postgresql-DB via JDBC from Java code?

Update: it does not work through JDBC.

Here is some working code for Frank Heikens answer :

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(); } 
+6
java postgresql jdbc backup
source share
3 answers

Why don't you use pg_dump ?

+6
source share

The Postgresql JDBC library now supports basic COPY operations. See http://jdbc.postgresql.org/documentation/publicapi/index.html?org/postgresql/copy/CopyManager.html

To back up the database, you need CopyOut from db to stream, and then cancel the recovery process using CopyIn .

+3
source share

I use DbUnit to backup the database from my java application:

DbUnit has the ability to export and import database data into and from XML datasets. Starting with version 2.0, DbUnit can also work with very large datasets when used in streaming mode.

0
source share

All Articles