Saturday, 24 December 2016

Restoring Database backup file using java code

This program restores the data from backup file to specified database. Here database used is postgres but the commands can be modified for other databases as well.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.InputStream;

public class dataBaseMigration {
public static void main(String[] args) throws Exception {

Runtime rv = Runtime.getRuntime();
        Process pRestore = null;
        ProcessBuilder pb;
        rv = Runtime.getRuntime();
        pb = new ProcessBuilder( 
            "C:\\Program Files\\PostgreSQL\\9.4\\bin\\pg_restore.exe", //modify this for other databases
            "--host", "localhost",
            "--port", "5432",
            "--username", "postgres",
            "--dbname", "test_database",
            "--role", "postgres",
            "--no-password",
            "--verbose",
           "E:\\pgBackup\\db_name.backup");

        pb.redirectErrorStream(true);
        pRestore = pb.start();
        //BufferedReader rRestore = new BufferedReader(new InputStreamReader(pRestore.getInputStream()));
       // InputStream is = pRestore.getInputStream();
        InputStreamReader isr = new InputStreamReader(pRestore.getInputStream());
        BufferedReader br = new BufferedReader(isr);
        String ll;
        while ((ll = br.readLine()) != null) {
         System.out.println(ll);
        }  
      }
}  

No comments:

Post a Comment