Saturday, 24 December 2016

Running .sql file from Java code

Demo on running .sql file from Java Code. Here postgres database is used but commands can be modified for other databases.

 public void createCleanUpProcedure()
  {
 
  Runtime rv = Runtime.getRuntime();
       Process pRestore = null;
       ProcessBuilder pb;
       rv = Runtime.getRuntime();
       pb = new ProcessBuilder(
           "C:\\Program Files\\PostgreSQL\\9.4\\bin\\psql.exe",
           "--host", "localhost",
           "--port", "5432",
           "--username", "postgres",
           "--dbname", "databaseName",            
           "--no-password",            
          "--file","E:\\pgBackup\\Test.sql");

       pb.redirectErrorStream(true);
       try {
pRestore = pb.start();
} catch (IOException e)
                             {
e.printStackTrace();
      }
     
       InputStreamReader isr = new InputStreamReader(pRestore.getInputStream());
       BufferedReader br = new BufferedReader(isr);
       String ll;
                try {
while ((ll = br.readLine()) != null) {
System.out.println(ll);
}

     } catch (IOException e) {
e.printStackTrace();
 }
  }



No comments:

Post a Comment