我已经安装了postgresql数据库,我必须通过我的java代码在这个数据库上发出一些命令。但是命令不是通过java代码执行的。如果我通过命令提示符触发相同的命令,则会执行。以下是我的java代码:
package frontend.guifx.pginstallation;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MyMultipleCommandsEx {
public static void main(String a[]) throws InterruptedException{
List<String> commands = new ArrayList<String>();
commands.add("CMD");
commands.add("/c");
commands.add("SET PGPASSWOR=test_admin");
commands.add(psql.exe --dbname=postgres --username=test_admin --port=5433 --command="\"CREATE schema test;\"");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("C:\\Program Files\\PostgreSQL\\9.5\\bin"));
try {
Process prs = pb.start();
int e = prs.waitFor();
System.out.println("Echo command executed, any errors? " + (e == 0 ? "No" : "Yes"));
System.out.println("Echo Output:\n" + output(prs.getInputStream()));
System.out.println("Error code:"+e);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}