在java程序中运行psql命令

在java程序中运行psql命令,java,postgresql,psql,Java,Postgresql,Psql,我需要使用java代码创建/删除/更改postgres表 我写了一个程序如下: public static void main(String[] args) throws IOException { System.out.println("Hello World!"); Process p = Runtime.getRuntime().exec("psql -U postgres -d testdb -h localhost -p 5433 -f D:\test.

我需要使用java代码创建/删除/更改postgres表

我写了一个程序如下:

public static void main(String[] args) throws IOException {
        System.out.println("Hello World!");
        Process p = Runtime.getRuntime().exec("psql -U postgres -d testdb -h localhost -p 5433 -f D:\test.sql");
    }
test.sql文件如下所示

Create TABLE MyTable1
(
    VersionNumber VARCHAR(32) NOT NUll
);

Create TABLE MyTable2
(
    VersionNumber VARCHAR(32) NOT NUll
);

Create TABLE MyTable3
(
    VersionNumber VARCHAR(32) NOT NUll
);
问题:

如果运行相同的psql命令:

psql-U postgres-d testdb-h localhost-p 5433-f d:\test.sql
在命令行中,它要求输入密码并创建表


但在java程序中,并没有提供密码的规定。请告诉我如何实现它。

首先,最好实际使用JDBC连接到数据库并运行SQL语句。如果设置为使用命令行psql,则可以使用
PGPASSWORD
环境变量设置密码:

String command = "psql -U postgres -d testdb -h localhost -p 5433 -f D:\test.sql";
String[] envVars = { "PGPASSWORD=yourpassword" };
Process p = Runtime.getRuntime().exec(command, envVars);
如有必要,您可以从
stdin
读取密码。但是,同样,最好通过JDBC执行此操作。

您可以使用:

psql-fd:\test.sqlpostgresql://postgres:password@本地主机:5433/testdb
关于 并在Windows操作系统上使用Java代码启动psql 和使用 以下轻微修改对我有效

    ProcessBuilder builder = new ProcessBuilder();
    String connUrl = "postgresql://user:password@host:port/dbname";
    String sqlFileToProcess = "--file=Disk:\\path\\to\\file.sql";
    builder.command("psql.exe", sqlFileToProcess, connUrl);
    builder.directory(new File("Disk:\\Path\\to\\psql\\containing\\folder"));
    Process process = builder.start();
    int exitCode = 0;
    try {
         exitCode = process.waitFor();
         int len;
         if ((len = process.getErrorStream().available()) > 0) {
             byte[] buf = new byte[len];
             process.getErrorStream().read(buf);
             System.err.println("Command error:\t\""+new String(buf)+"\"");
         }
    } catch (InterruptedException e) {
         e.printStackTrace();
    }
   assert exitCode == 0;
不知道为什么,但如果:

-f Disk:\\path\\to\\file.sql
Java代码中的参数抛出:

Command error:  "unrecognized win32 error code: 123 psql: error:  Disk:/path/to/file.sql: Invalid argument
"

(注意otput和input中斜杠和反斜杠的重定向)

对不起。。这不管用。如果我直接将PGPASSWORD设置为系统变量,那么它就可以工作。如果我从系统变量中删除条目并尝试使用您的方法,那么它将不起作用。你能不能也从你这边检查一下。我用的是postgres 10.5版本。可以吗