I am writing in Java some code to automatically restore a backup from the cloud. Herefor I need to open psql, terminate connections, exit psql and drop database in one command from (CMD) command line tool at Windows, so that Java can execute this in once. Respectively these are the seperate steps (I think);
psql -h localhost -p 5433 -U postgres -w OC_A -c '
SELECT
pg_terminate_backend(pid)
FROM
pg_stat_activity
WHERE
pid <> pg_backend_pid();
/q postgres-# \q ;'
dropdb -h localhost -p 5433 -U postgres -w OC_A
I have put these steps into one single cmd command like;
// 2 - terminate db connections, delete based on config db's
String terminateSQLconnecitons= "\npsql -h "+ postgresHost + " -p " + postgresPort + " -U " + postgresUsername + " -w " + postgresDbname + " -c "+
"\'\nSELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid();\n/q postgres-# \\q ;'" ;
int terminateSQLconnecitonsResult = cmdExe(terminateSQLconnecitons);
if (terminateSQLconnecitonsResult == 0) {
System.out.println("Connections terminated");
} else {
System.out.println("CONNECTIONS NOT TERMINATED");
}
public static int cmdExe(String cmd) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.redirectErrorStream(true);
processBuilder.command("cmd.exe", "/c", cmd);
System.out.println(cmd);
int exitCode = -1;
try {
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
exitCode = process.waitFor();
System.out.println("Result :" + exitCode);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return exitCode;
}
Where/what do I need to change to execute these steps in one command in Java?
EDIT 1; I have now already seperate steps but seems not working..I don't get it why.
// 2 - terminate db connections, delete based on config db's
String terminateSQLconnecitons= "\npsql -h "+ postgresHost + " -p " + postgresPort + " -U " + postgresUsername + " -w " + postgresDbname + " -c "+
"\'\nSELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid();\n/q postgres-# \\q ;'" ;
int terminateSQLconnecitonsResult = cmdExe(terminateSQLconnecitons);
if (terminateSQLconnecitonsResult == 0) {
System.out.println("Connections terminated");
} else {
System.out.println("CONNECTIONS NOT TERMINATED");
}
String DeleteCMD= "\ndropdb -h "+ postgresHost + " -p " + postgresPort + " -U " + postgresUsername + " -w " + postgresDbname;
int cmdResult = cmdExe(DeleteCMD);
if (cmdResult == 0) {
System.out.println("Database " + postgresDbname + " deleted");
} else {
System.out.println("Database " + postgresDbname + " NOT deleted");
}