Invoke postgres commands via Java Runtime.getruntime.exec()
Initially I ran this code without the leading "cmd"
and I received an access denied message. Postgres is being run as a service by an account that cannot be logged into and I am an administrator running this application. The attempt with "cmd"
included returns me no input. My question is how do I go about executing these statements to achieve the resulting files and data changes?
String[] psqlCommands = {"cmd ",postgresLocation, " -dDatabase ", " -UUser ",
"-c ", "UPDATE host.user SET service = 1 WHERE service = 1;" +
"UPDATE host.permission 开发者_Go百科SET service = 1 WHERE service = 2"};
Runtime.getRuntime().exec(psqlCommands);
String[] pgDumpCommands = {"cmd ", postgresLocation, " --data-only ",
"-t host.user_info -t host.permission -t host.group -t host.account -t host.password " +
"-UUser Database> "
+ DATA + "\\dataExport.sql"};
Runtime.getRuntime().exec(pgDumpCommands);
The exception that is generated is an Access Denied
exception that is on the Postgres_Bin
directory. I will post a trace once I get the necessary materials.
Exception in thread "main" java.io.IOException: Cannot run program "d:\program f
iles\postgres\bin": CreateProcess error=5, Access is denied
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at Thing.main(Thing.java:85)
Caused by: java.io.IOException: CreateProcess error=5, Access is denied
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 4 more
From the error it looks like you're trying to run the directory, and not appending "psql" or "pg_dump" to get the actual executable name.
I would also believe you wouldn't need to include the "cmd" on the beginning, so try taking that out again.
java.io.IOException: Cannot run program "d:\program files\postgres\bin"
This error indicates that the spaces in the path confuse the exec() call (and the directory bin is indeed nothing that Windows can run)
Make sure you enclose the full path to the .exe with double quotes because of the spaces.
I think using ProcessBuilder is recommended over using exec() as you can specify the arguments and the program to run with different parameters avoiding the escaping of path names with spaces.
First if you want to run something in context of windows shell you have to use cmd /c
. Otherwise you are just running cmd itself. This is the reason that you do not get anything.
When fix your code you are expected to get access denied exactly as you got when you did not use cmd because it seems that you do not have enough permissions. To solve the problem
1. fix your permissions
2. if it is impossible try to run external process as different user using runas
command.
精彩评论