A logo showing the text blog.marcnuri.com
Español
Home»Java»Java App for PostgreSQL scheduled backups using pg_dump (Windows only)

Recent Posts

  • Fabric8 Kubernetes Client 6.5.0 is now available!
  • Eclipse JKube 1.11 is now available!
  • Fabric8 Kubernetes Client 6.4.1 is now available!
  • I bought an iPad
  • Three years at Red Hat

Categories

  • Front-end
  • Java
  • JavaScript
  • Legacy
  • Operations
  • Personal
  • Pet projects
  • Tools

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • December 2019
  • October 2019
  • September 2019
  • July 2019
  • March 2019
  • November 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • December 2017
  • July 2017
  • December 2015
  • November 2015
  • November 2008
  • November 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007

Java App for PostgreSQL scheduled backups using pg_dump (Windows only)

2007-03-27 in Java / Legacy tagged Backup / cron / Database / Java / PostgreSQL by Marc Nuri | Last updated: 2021-02-06

Today I'll show you an easy way to automate your database backup dumps with a java application that runs on the background. This simple app will generate a backup of your database and will name it with today's date. It's not really the java program interacting with the database, but the app interacting with the command line program pg_dump.

The procedure is quite simple. First, we generate a filename with today's date. Then we check if the file exists. Finally, we call the pg_dump with the appropriate parameters and the backup is generated

1public void backupPGSQL(){
2  try{
3    Runtime r =Runtime.getRuntime();
4    //Path to the place we store our backup
5    String rutaCT = "C:\\BAKCUPS\\";
6    //PostgreSQL variables
7    String IP = "192.168.1.1";
8    String user = "postgres";
9    String dbase = "yourDataBase";
10    String password = "yourPassword";
11    Process p;
12    ProcessBuilder pb;
13    InputStreamReader reader;
14    BufferedReader buf_reader;
15    String line;
16    //We build a string with today's date (This will be the backup's filename)
17    java.util.TimeZone zonah = java.util.TimeZone.getTimeZone("GMT+1");
18    java.util.Calendar Calendario = java.util.GregorianCalendar.getInstance( zonah, new java.util.Locale("es"));
19    java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMdd");
20    StringBuffer date = new StringBuffer();
21    date.append(df.format(Calendario.getTime()));
22    java.io.File file = new java.io.File(rutaCT);
23    // We test if the path to our programs exists
24    if (file.exists()) {
25      // We then test if the file we're going to generate exist too. If so we will delete it
26      StringBuffer fechafile = new StringBuffer();
27      fechafile.append(rutaCT);
28      fechafile.append(date.toString());
29      fechafile.append(".backup");
30      java.io.File ficherofile = new java.io.File(fechafile.toString());
31      if (ficherofile.exists()) {
32        ficherofile.delete();
33      }
34      r = Runtime.getRuntime();
35      pb = new ProcessBuilder(rutaCT + "pg_dump.exe", "-f", fechafile.toString(),
36          "-F", "c", "-Z", "9", "-v", "-o", "-h",IP, "-U", user, dbase);
37      pb.environment().put("PGPASSWORD", password);
38      pb.redirectErrorStream(true);
39      p = pb.start();
40      try {
41        InputStream is = p.getInputStream();
42        InputStreamReader isr = new InputStreamReader(is);
43        BufferedReader br = new BufferedReader(isr);
44        String ll;
45        while ((ll = br.readLine()) != null) {
46          System.out.println(ll);
47        }
48      } catch (IOException e) {
49        log("ERROR "+e.getMessage(), e);
50      }
51    }
52  } catch(IOException x) {
53    System.err.println("Could not invoke browser, command=");
54    System.err.println("Caught: " + x.getMessage());
55  }
56}

To run the above method you will need to have pg_dump.exe and the necessary dll files in the backups directory.

We can also schedule the task to be run once a day so we can have a fresh backup every night:

1TimerTask backupTask = new TimerTask() {
2  public void run(){
3    backupPGSQL();
4  }
5};
6// We schedule the task to be run every 24 hours
7Timer time = new Timer();
8time.scheduleAtFixedRate(backupTask, new Date(),1000*60*60*24);
9// Even better, we can schedule the task to be run every 24 hours at a fixed time.
10// (remember to remove the above line if you prefer this method)
11Calendar taskTime = Calendar.getInstance();
12// We want the task to be run at 1 o'clock in the morning
13taskTime.set(Calendar.HOUR_OF_DAY, 1);
14// We clear the rest of the values for the calendar
15taskTime.clear(Calendar.MINUTE);
16taskTime.clear(Calendar.SECOND);
17taskTime.clear(Calendar.MILLISECOND);
18// If the time has already passed, we add another day to the count, so the task will start tomorrow
19if (now.after(taskTime)) {
20  taskTime.add(Calendar.DAY_OF_YEAR, 1);
21}
22Date startingDate = taskTime.getTime();
23time.scheduleAtFixedRate(backupTask, startingDate, 1000L*60*60*24);
Twitter iconFacebook iconLinkedIn iconPinterest iconEmail icon

Comments in "Java App for PostgreSQL scheduled backups using pg_dump (Windows only)"

  • Avatar for Araz
    Araz
    2008-08-19 08:33
    Thank you very much..
  • Avatar for lukasz
    lukasz
    2009-03-28 14:28
    Thanks. Work good ;-)
  • Avatar for Rupendra
    Rupendra
    2010-11-23 18:08
    Thank you very much. It worked and will help me a lot in automating a set of tedious tasks.
  • Avatar for Blanka
    Blanka
    2012-11-14 09:54
    Sir. Best tit. I mean tut. Thanks crap..love it shit bro :)
  • Avatar for Deepali
    Deepali
    2013-10-14 09:57
    It's fantastic, I was in search of this, I would try my best to work on this. Please be kind to help me if I have any queries. :)
  • Avatar for fayez
    fayez
    2013-12-02 02:06
    really really ... you are great thnxxxxxxxxxxxxxxxxxx
  • Avatar for csjawad
    csjawad
    2014-06-06 14:13
    Weldone Sir.
  • Avatar for Codemonkey
    Codemonkey
    2014-09-26 14:48
    I used snippets of your code in my project and they works great. Thank you.
  • Avatar for utpal
    utpal
    2015-05-11 07:32
    please help me, how i run this above code in netbeans.

Post navigation

← Displaying a jTable inside another jTable // JTable cellRendererChoosing a printer programmatically in Jasper Reports →
© 2007 - 2023 Marc Nuri